5

i am using a bash terminal and i have a .txt file in which i got three columns of Hex numbers separated by a space. I'd like to convert them to decimal numbers. I tried the last command from here Converting hexadecimal to decimal using awk or sed but it converts the first column only, put a comma among the columns and put a 0 on the second and third columns. to have a more clear idea of what i have and what i want:

Input

30c8 ffbc 3e80        
30c8 ffbc 3e81     

Output:

12488 65468 16000
12488 65468 16001
Community
  • 1
  • 1
merlinuxxx
  • 119
  • 1
  • 6

5 Answers5

5

Another approach would be to say:

$ while read a b c; do echo $((16#$a)) $((16#$b)) $((16#$c)); done < inputfile
12488 65468 16000
12488 65468 16001
devnull
  • 118,548
  • 33
  • 236
  • 227
1

As printf "%d" 0xFF returns 255 and so on, you can do:

$ while read p q r; do printf "%d %d %d\n" 0x$p 0x$q 0x$r; done < input
12488 65468 16000
12488 65468 16001

That is, we read 3 variables on each line and we save them as p, q, r. Then we print them with the above form, so that they get printed as decimal.

In case you have another field separator, you can use IFS to indicate so:

$ cat a
30c8,ffbc,3e80
30c8,ffbc,3e81
$ while IFS=, read p q r; do printf "%d %d %d\n" 0x$p 0x$q 0x$r; done < a
12488 65468 16000
12488 65468 16001
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

You're using another separator, in the original question the separator was "," - you use a blank space.

Try this command instead:

gawk --non-decimal-data '{for(i=1;i<=NF;i++) $i=sprintf("%d","0x"$i)}1' input
Stefan M
  • 868
  • 6
  • 17
  • The `BEGIN` block doesn't do anything here as `OFS==FS` by default and it's better to use `i<=NF` than hard code the upper limit in the loop. – Chris Seymour Sep 19 '13 at 13:24
  • That's correct. I was trying to show user2795403 what really is different from the command that he copied. I'm editing my answer as you suggested. – Stefan M Sep 19 '13 at 13:36
1

Using gawk

gawk --non-decimal-data '{for(i=1;i<=NF;i++) $i=sprintf("%d","0x"$i)}1' file
12488 65468 16000
12488 65468 16001
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Jotne
  • 40,548
  • 12
  • 51
  • 55
0

In awk you would do:

$ awk '{for(i=1;i<=NF;i++)printf "%d%s",strtonum("0x"$i),(i==NF?RS:FS)}' file
12488 65468 16000
12488 65468 16001
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202