serg dan
serg dan

Reputation: 33

How to use awk to convert field from hexa to decimal

I am extracting an snmp value that is in hex and I want the output to be in decimal, but i am not able to execute the shell command in awk for field $2 and $4

hex output of the snmp is :

00 01 00 30

trying to convert using this command:

snmpwalk -v 2c -c public 10.10.10.1 1.3.6.1.4.1.2272.1.3.3.1.3.206 | awk '{ print 'echo "'ibase=16; $2'|bc"' ; 'echo "'ibase=16; $4'|bc"' }'

also tried this

| awk '{ print $2, system('echo "ibase=16; $2"|bc') }' 

but I am not able to get it right

the output should look like :

1 48

Upvotes: 1

Views: 283

Answers (2)

Sahil Aggarwal
Sahil Aggarwal

Reputation: 1351

Suppose your command outputs like this :

[root@instance-1 ~]# cat ggg
00 01 00 30

Now run the following command

[root@instance-1 ~]# cat ggg | xargs -I {} -d ' ' sh -c 'echo "obase=10; ibase=16; {}" | bc' 

0 1 0 48

in the above command replace "cat ggg" with snmpwalk -v 2c -c public 10.10.10.1 1.3.6.1.4.1.2272.1.3.3.1.3.206 .

Upvotes: 0

James Brown
James Brown

Reputation: 37404

Here is one for GNU awk:

$ echo 00 01 00 30 | gawk  '{print strtonum("0x" $2),strtonum("0x" $4)}'
1 48

Here is one for other awks (tested on Busybox awk, mawk and awk-20121220):

$ echo 00 01 00 30 | mawk  '{printf "%d %d\n","0x" $2, "0x" $4}'
1 48

Upvotes: 2

Related Questions