How to print ASCII value of a character using basi

2020-02-09 03:30发布

I need to print the ASCII value of the given character in awk only.

Below code gives 0 as output:

echo a | awk '{ printf("%d \n",$1); }'

标签: unix shell awk
3条回答
够拽才男人
2楼-- · 2020-02-09 03:43

Using only basic awk (not even gawk, so the below should work on all BSD and Linux variants):

$ echo a | awk 'BEGIN{for(n=0;n<256;n++)ord[sprintf("%c",n)]=n}{print ord[$1]}'
97

Here's the opposite direction (for completeness):

$ echo 97 | awk 'BEGIN{for(n=0;n<256;n++)chr[n]=sprintf("%c",n)}{print chr[$1]}'
a

Basic premise is to use a lookup table.

查看更多
Evening l夕情丶
3楼-- · 2020-02-09 03:48

see the awk manual for ordinal functions you can use. But since you are using awk, you should be on some version of shell, eg bash. so why not use the shell?

$ printf "%d" "'a"
97
查看更多
虎瘦雄心在
4楼-- · 2020-02-09 03:57

It seems this is not a trivial problem. I found this approach using a lookup array, which should work for A-Z at least:

 BEGIN { convert="ABCDEFGHIJKLMNOPQRSTUVWXYZ" } 
       { num=index(convert,substr($0,2,1))+64; print num }
查看更多
登录 后发表回答