convert first column from hex to decimal using awk

5.2k views Asked by At

I have a log file which contains logs time stamp in Hexadecimal in column one and then log text in rest of the columns.For example:

B60C0056: aaa1 bb1 ccc1 ddd1 eee1 fff
B60C0056: aaa2 bb2 ccc2 ddd2 eee2 fff
B60C0057: aaa3 bb3 ccc3 ddd3 eee3 fff
B60C0058: aaa4 bb4 ccc4 ddd4 eee4 fff
B60C0059: aaa5 bb5 ccc5 ddd5 eee5 fff

I need to convert the first column to decimal and I am using the following way to do so,but don't know how to implement this for the whole file.

while read line
do
echo -e "$line"|awk '{print $1,$2,$3,$4,$5,$6}'
done <temp

But how to convert $1 to the decimal value?

echo "ibase=16; `awk '{print $1}'`" | bc
3

There are 3 answers

1
Wintermute On BEST ANSWER

Using GNU awk:

gawk --non-decimal-data '{ $1 = sprintf("%d:", "0x" $1) } 1' filename

This is a little bastardized: "0x" $1 concatenates 0x and the first field as string, sprintf then proceeds to interpret it as a number, which is parsed as hexadecimal because of the 0x and --non-decimal-data. This will only work with GNU awk.

Alternatively, consider using Perl:

perl -pe 's/^[[:xdigit:]]+/hex($&)/e' filename

This should work everywhere where Perl is available (which should be everywhere, really).

EDIT: Better Perl solution.

4
anubhava On

awk's strtonum function can take care of that:

awk 'BEGIN{FS=OFS=":"} {$1=strtonum("0x" $1)} 1' file
3054239830: aaa1 bb1 ccc1 ddd1 eee1 fff
3054239830: aaa2 bb2 ccc2 ddd2 eee2 fff
3054239831: aaa3 bb3 ccc3 ddd3 eee3 fff
3054239832: aaa4 bb4 ccc4 ddd4 eee4 fff
3054239833: aaa5 bb5 ccc5 ddd5 eee5 fff
0
Fredrik Pihl On

Try:

$ awk --non-decimal-data -F':' '{printf "%d:%s\n", "0x" $1, $2}' INPUT
3054239830: aaa1 bb1 ccc1 ddd1 eee1 fff
3054239830: aaa2 bb2 ccc2 ddd2 eee2 fff
3054239831: aaa3 bb3 ccc3 ddd3 eee3 fff
3054239832: aaa4 bb4 ccc4 ddd4 eee4 fff
3054239833: aaa5 bb5 ccc5 ddd5 eee5 fff