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); }'
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); }'
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
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.
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 }