Convert hex to dec using awk

Asked by At

I have a large csv files , where few columns values are in hex. I need to convert them into decimal. The CSV files are very big. So If I process each row , then it takes a lot of time to execute the script. So I want to know how this can be done parallely by using awk command

If I process the code line by line it works.

I process the files like this.

while read -r line;
do
    start_time=`echo "$line"|awk -F "," '{ print $1 }'`
    end_time=`echo "$line"|awk -F "," '{ print $2 }'`
    st_time=$((16#$start_time))
    en_time=$((16#$end_time))

Then I echo the required fields to output file.

Sample Input file:

16a91f90539,16a91f931a9,e,0
16a91f90bab,16a91f931a9,e,0

Expected output:

1557227177273,1557227188649,e,0
1557227178923,1557227188649,e,0

I need to know how the statement "((16#$start_time))" , can be used in awk. I tried

awk -F',' '{OFS=",";}{print '"(($1#16))"','$en_time',$3'

But this syntax does not work.

2 Answers

0
geronimo On

You can execute system calls from withnig awk with system(...). Don't forget to close the command afterwards.

awk -F "," '{ cmd=sprintf("echo $((0x%s))\n", $1); system(cmd); close(cmd); }' input

(for some reason the system call does not work with $((16#...)) on my system, but does work with $((0x...)))

With getline you can assign the echo'ed output to a variable. See https://www.gnu.org/software/gawk/manual/html_node/Getline-Notes.html to get you started.

3
Ed Morton On

With GNU awk for strtonum() you don't need to spawn multiple shells on each input line:

$ awk 'BEGIN{FS=OFS=","} {for (i=1;i<=2;i++) $i=strtonum("0x"$i)} 1' file
1557227177273,1557227188649,e,0
1557227178923,1557227188649,e,0