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

前端 未结 3 855
温柔的废话
温柔的废话 2020-12-09 10:09

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)         


        
3条回答
  •  旧时难觅i
    2020-12-09 11:00

    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.

提交回复
热议问题