Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file name x

$ cat x
1A34532112345

I wants to print in hex using awk I written a script (with help from web)

fold -1 /home/cscape/Desktop/x | gawk '{ printf("%s , %X\n",$0, int($0) )}' 

But output for each char is 0

$ fold -1 /home/cscape/Desktop/x | gawk '{ printf("%s , %X\n",$0, int($0) )}'
1 , 1
A , 0
3 , 3
4 , 4
5 , 5
3 , 3
2 , 2
1 , 1
1 , 1
2 , 2
3 , 3
4 , 4
5 , 5

Why 0 for A. even with %d. I wants to print ASCII value of A as HEX.

share|improve this question
    
Not sure what you are trying to accomplish, but it'll probably work if you change the file contents to contain a single character per line. If that gives the output you are looking for, then we can help you change the awk script. Also what's wrong with hexdump -C? –  jippie Dec 15 '12 at 9:29
add comment

2 Answers

up vote 2 down vote accepted

awk will silently convert strings to numbers. Which number? The number you get by taking the initial decimal digits of the string (this may be just "", if the string is empty or doesn't begin with any decimal digits, as is the case with "A") and converting them to a number. "" gets converted to 0. So all of these would be converted to 0:

  • "0"
  • "0text"
  • "text"
  • ""

awk only converts strings to numbers in this way when a number is needed. In "0text" + 1, a number is needed, so the result will be 1. In just plain "0text", a number isn't needed, so no conversion takes place. In printf("%d", "0text"), a number again is needed, so the string will be converted to a number.

What you are looking for is an ord function, which isn't a native function in awk. The gawk documentation describes how to write such a function in awk.

share|improve this answer
    
Thanks ..helpful to get my work done and my concept is now clear. –  Grijesh Chauhan Dec 15 '12 at 10:24
add comment

If you don't have to use awk, you might look at od ("octal dump"):

$ echo 1A34532112345 | od -t x1
0000000 31 41 33 34 35 33 32 31 31 32 33 34 35 0a
0000016
share|improve this answer
    
Yes I learn today this also...Thanks! –  Grijesh Chauhan Dec 15 '12 at 18:07
    
can you help me on this question –  Grijesh Chauhan Dec 15 '12 at 18:07
add comment

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.