使用awk或sed将十六进制转换为十进制

时间:2013-06-05 07:40:46

标签: shell scripting sed awk

我有这样的数据,用逗号分隔:

18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG1,2fe3,c7b1
18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG2,2fe3,c7b2
18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG3,2fe3,c7b3
03:25:55,Othercauses,N_Pancamukti,N_PancamuktiMG1,2f50,c775
03:25:55,Othercauses,N_Pancamukti,N_PancamuktiMG2,2f50,c776

我需要将最后两列转换为十进制,如下所示:

18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG1,12259,51121
18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG2,12259,51122
18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG3,12259,51123
03:25:55,Othercauses,N_Pancamukti,N_PancamuktiMG1,12112,51061
03:25:55,Othercauses,N_Pancamukti,N_PancamuktiMG2,12112,51062

我已经尝试过这个:
cat | nawk -F,'{printf“%d \ n”,$ 1}'

我只得零作为输出:
0 0 0 0 0 0 0 0 0

1 个答案:

答案 0 :(得分:3)

使用Perl:

perl -lpe 's/([^,]*),([^,]*)$/hex($1).",".hex($2)/e' input

输出:

18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG1,12259,51121
18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG2,12259,51122
18:22:05,OtherOMoperation,BatuAmpar,BatuAmparMG3,12259,51123
03:25:55,Othercauses,N_Pancamukti,N_PancamuktiMG1,12112,51061
03:25:55,Othercauses,N_Pancamukti,N_PancamuktiMG2,12112,51062

和gawk中的类似:

gawk --non-decimal-data -F, '
      BEGIN{OFS=FS}{for(i=5;i<7;i++) $i=sprintf("%d","0x"$i)}1' input