将15位数字转换为十六进制

时间:2014-05-06 09:10:34

标签: awk gawk

我需要输出一个15位数字输入到逗号分隔的十六进制字符串,但我似乎无法从第一个字符开始,这是我到目前为止:

echo "012345678912345" |awk 'BEGIN{FS=OFS=""}{for (i=1;i<=NF;i++) {if (i%1==0) $i=$i ",0x3"}}1'

0,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x31,0x32,0x33,0x34,0x35,0x3

echo 123456789123456 | awk '$1=$1' FS= OFS=",0x3"

1,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x31,0x32,0x33,0x34,0x35,0x36

如何让它在开始时插入0x3或在开始时添加一个随机字符然后将其删除?结果id想要输入012345678912345将是:

0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x31,0x32,0x33,0x34,0x35

2 个答案:

答案 0 :(得分:1)

awk -v OFS=",0x3" -v FS="" '$1="0x3"$1'

以你的例子:

kent$  echo "012345678912345" |awk -v OFS=",0x3" -v FS="" '$1="0x3"$1'   
0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x31,0x32,0x33,0x34,0x35

答案 1 :(得分:0)

如果您对非awk方法持开放态度(只有每个平台awk也有sed),请尝试:

pax> echo "012345678912345" | sed 's/\(.\)/,0x3\1/g;s/^,//'
0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x31,0x32,0x33,0x34,0x35

sed命令序列由两部分组成:

  • 第一个s/\(.\)/,0x3\1/g为每个字符添加字符串,0x3前缀。
  • 第二个,s/^,//摆脱了第一个逗号。