awkgawk

About awk and integer to ASCII character conversion


Just to make sure, is it really that using awk (Gnu awk at least) I can convert:

from octal to ASCII by:

print "\101"         # or a="\101"
A

from hex to ASCII:

print "\x41"         # or b="\x41"
B

but from decimal to ASCII I have to:

$ printf "%c\n", 67  # or c=sprintf("%c", 67)
C

There is no secret print "\?67" in that RTFM (Memo) I missed?

I'm trying to get character frequencies from $0="aabccc" like:

for(i=141; i<143; i++) a=a gsub("\\"i, ""); print a
213

but using decimals (instead of octals in above example). The decimalistic approach seem awfully long:

$ cat foo
aabccc
$ awk '{for(i=97;i<=99;i++){c=sprintf("%c",i);a=a gsub(c,"")} print a}' foo
213

It got used here.


Solution

  • No, \nnn is octal and \xnn is hex - that's all there is for including characters you cannot include as-is in strings and you should always use the octal, not the hex, representation for robustness (see, for example, http://awk.freeshell.org/PrintASingleQuote).

    I don't understand the last part of your question where you state what you're trying to do with this - provide concise, testable sample input and expected output and I'm sure someone can help you do it the right way, whatever it is.

    Is this what you're trying to do?

    $ awk 'BEGIN{for (i=0141; i<0143; i++) print i}'
    97
    98