我已经与一些类似的问题作斗争,我相信已经讨论过了,但我真的找不到出路:如果你的文件有数据,例如下面(十六进制值可以是任何东西,但固定为1字节),你想转换每个十六进制到十进制,并保持它在下面的格式,而不是十六进制,你显示十进制,仍然逗号分隔?- 请注意,数据线的数量不是固定的,它可以由任何数量。
例一:
0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51
0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a
0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0
0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51
0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a
0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0
0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51
0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a
0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0
示例2:与上面相同,但假设它前面有数据名称:
X:0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51
Y:0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a
Z:0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0
X:0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51
Y:0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a
Z:0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0
X:0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51,0x51
Y:0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a
Z:0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0,0xf0
所以我花了一些时间来了解bash grep,sed等。由于我完全不是软件的家伙,我设法发挥和过滤出一些文本文件在正确的格式下,我想了解如何操作字符串与一个以上的值和上述例子将真正帮助。先谢了。
我确实尝试了printf
,echo
,当文本文件中的每个字符串都有一个值时,我可以使用它们,例如:如果我使用包含数据数据文件
0xff
0xff
0xff
0xff
0xff
.
.
.
.
.
.
..
0xff
所有工作正常,可以转换为printf
功能:这是在另一个线程中找到的:
while read line
do
printf '%d' $line
done < file
上面的工程伟大的一个十六进制值行:这是否可以调整到与我的例子一起工作,或者有更好的方法?
6条答案
按热度按时间cbeh67ev1#
您可以使用(GNU)Awk及其
strtonum
函数,该函数将以0x
开头的字符串转换为十进制数。,
处拆分,从1
列开始:,
或:
处拆分,并从列2
开始::
也将被转换为,
。如果不需要这样做,可以分别打印列1
、2
和其余列:h7appiyu2#
一个广义的
awk
解-保存到一个文件中,运行每个示例集:
只是为了练习,基本的
bash
也是如此。对于这么小的数据集,差异是无关紧要的。
如果输入很大,
awk
会更快。ghg1uchk3#
我会使用
perl
。对于您的第一个案例:第二个,前缀是:
u59ebvdq4#
一个简单的Bash解决方案是让Bash像往常一样解析整数。对于实施例2:
然后
to_dec < file
给出示例2的预期输出。示例1的to_dec
将简单得多,因为在这种情况下不需要辅助数组;只要读一下数字:至于示例2的数学运算,在注解中要求,在纯Bash中可以创建以行前缀命名的函数,然后在数组上执行它们。无论如何,它不会是“高效的”;它是Bash。(另外,据推测,Bash只有整数除法;为了避免这种情况,可以使用某种定点表示,但这在Bash中太过笨拙了。)
为了提高效率和浮点运算,
awk
可以提供帮助:对于大型数据处理,使用更低级的编程语言进行适当的实现会更有效。
vktxenjb5#
GNU AWK
6qftjkof6#