壳牌:在文件转换为文本文件的第一个字段从十进制为十六进制 [英] Shell: In-file converting first field of a text file from decimal to hexadecimal

查看:197
本文介绍了壳牌:在文件转换为文本文件的第一个字段从十进制为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的示例文本文件:

This is my example text file:

$ cat RealVNC\ MRU.reg
"10"="Lamborghini-:1"
"16"="Terminus-"
"20"="Midnighter-:5915"
"35"="ThreepWood-:1"
"81"="Midnighter-:1"
"58"="Midnighter-"

和我想的转化第一个字段的值(间数)从< STRONG>十进制为十六进制(它是Windows .reg文件,所以我meesed起来思考数字是一个十进制基地,现在的文件太长手动编辑)。

And I would like to convert values of the first field (the numbers between "") from decimal to hexadecimal (it is a .reg file for Windows, so I meesed it up thinking the numbers were in a decimal base, and now the file is too long to manually edit).

结果示例,我需要获得:

Example result that I need to obtain:

$ cat Hex\ RealVNC\ MRU.reg
"0A"="Lamborghini-:1"
"10"="Terminus-"
"14"="Midnighter-:5915"
"23"="ThreepWood-:1"
"51"="Midnighter-:1"
"3A"="Midnighter-"

如可以看到的,<强>仅数字已经改变。
由此得出的数字必须是长两个字符(注册表编辑认为它们不同)。结果
在线路的为了更改这里不烦,但我认为它会更干净的解决方案,这并不改变它。

As can be seen, only the numbers have changed. Resulting numbers must be two characters long (RegEdit considers them different).
Changes in the order of the lines don't bother here, but I think it would be more "clean" a solution that doesn't change it.

我不希望任何数量(无论是十进制或十六进制)将有超过 2字符,但认为这种可能性将是最好的(因为它是一个更通用的解决方案)的解决方案

I don't expect any number (be it decimal or hex) will have more than 2 characters, but a solution that considers this possibility will be best (as it is a more generic solution).

我迄今已检测:

$ cat RealVNC\ MRU.reg | awk -F \" '{print $2}'
10
16
20
35
81
58

但我不知道是谁在网上所做的更改从十二月十六进制。

But I don't know who to in-line make the changes from dec to hex.

我的外壳一般是猛砸,但其他壳衍生化解决方案(如Perl或Python)被接受了。

My shell is usually Bash, but other shell-derivated solutions (like Perl or Python) are accepted too.

推荐答案

一个简单的 AWK

awk -F\" '$2=sprintf("%02X", $2)' OFS=\" file
"0A"="Lamborghini-:1"
"10"="Terminus-"
"14"="Midnighter-:5915"
"23"="ThreepWood-:1"
"51"="Midnighter-:1"
"3A"="Midnighter-"

说明


  • -F \\:设置字段分隔符( FS )以

  • -F\" : sets field separator (FS) to "

$ 2 = sprintf的(%02X,$ 2) $ 2 分配给它的打印
版本使用在十六进制%02X 面膜(的sprintf
字母A为十六进制数字大于9F和一个两位数
宽度与 0 填充

$2=sprintf("%02X", $2) : $2 is assigned to it’s printed version ( sprintf) with a %02X mask in hexadecimal using the letters 'A' to 'F' for hex digits greater than 9 and a two digits width with 0 padding

OFS = \\:设置 0 本安输出的 FS ,以匹配 FS

OFS=\" : sets the Output FS to match FS

$ 2 分配永远是真正的并没有额外的行动给出了 AWK 始终显示的结果,因为它的默认操作。

The $2 assignation is always true and no additional action is given , awk always displays the results as it's default action.

这篇关于壳牌:在文件转换为文本文件的第一个字段从十进制为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆