Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

shell

unix

awk

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); }'
like image 545
Venkataramesh Kommoju Avatar asked Mar 23 '10 10:03

Venkataramesh Kommoju


1 Answers

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.

like image 181
Devin Teske Avatar answered Sep 19 '22 18:09

Devin Teske