开发者

How to print ASCII value of a character using basic awk only

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

Below code gives 0 as output:

echo a开发者_C百科 | awk '{ printf("%d \n",$1); }'


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.


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


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 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜