Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How do I convert an ASCII char to ASCII HEX in a AWK script?

I want loop by a range of letter

example

for(i="a"; i<"g"; i++)
 print i;

NOTE: I want loop by a range from hex representation and print the character.

share|improve this question

2 Answers 2

Sounds to me like you don't really need all the characters...

$ awk 'BEGIN { chartable="abcdefghij" ; for (i=index(chartable, "a"); i<index(chartable, "g"); i++) { print substr(chartable, i, 1) } }'
a
b
c
d
e
f
share|improve this answer

Build a table containing all the ASCII characters and use the awk builtin index() to lookup characters in the table. Then use sprintf() to convert the decimal value returned by index() to hex.

BEGIN {
    for (i = 0; i < 128; i++) {
       table = sprintf("%s%c", table, i);
    }
}

function chartohex (char) {
    return sprintf("0x%x", index(table, char));
}

END { # examples
   print chartohex("a");
   print chartohex("A");
   print chartohex("!");
}

Put this code in the file "foo" and run awk -f foo < /dev/null and you'll see the ASCII values for "a", "A" and "!" printed in hexadecimal.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.