merlinuxxx
merlinuxxx

Reputation: 119

converting hexadecimal to decimal from a csv-like txt file

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

Upvotes: 5

Views: 3270

Answers (5)

Stefan M
Stefan M

Reputation: 889

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

Upvotes: 1

Jotne
Jotne

Reputation: 41456

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

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

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

Upvotes: 0

devnull
devnull

Reputation: 123458

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

Upvotes: 5

fedorqui
fedorqui

Reputation: 289565

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

Upvotes: 1

Related Questions