为什么sed不能替换二进制文件中的0x24字节?

S-t*_*ace 5 binary hex replace binaryfiles sed

我想将二进制文件中的一些字节替换为另一个字节.通过创建样本(6个字节长)文件

echo -ne '\x8f\x15\x42\x02\x24\xc2' > test
Run Code Online (Sandbox Code Playgroud)

然后尝试通过sed 将bytes \ x15\x42\x02替换为\ x12\x12\x02:

sed 's \x15\x42\x02 \x12\x12\x02 g' test > test1
Run Code Online (Sandbox Code Playgroud)

sed替换字节:

cat test test1 | xxd -c 6
0000000: 8f15 4202 24c2  ..B.$.
0000006: 8f12 1202 24c2  ....$.
           ^^ ^^^^
Run Code Online (Sandbox Code Playgroud)

尝试然后将bytes \ x42\x02\x24替换为\ x12\x02\x24:

sed 's \x42\x02\x24 \x12\x02\x24 g' test > test2
Run Code Online (Sandbox Code Playgroud)

sed NOT替换字节:

cat test test2 | xxd -c 6
0000000: 8f15 4202 24c2  ..B.$.
0000006: 8f15 4202 24c2  ..B.$.
              ^^^^ ^^
Run Code Online (Sandbox Code Playgroud)

怎么了?我有sed(GNU sed)4.2.2(Kubuntu 13.10)

谢谢.

小智 8

这是因为0x24$角色的十六进制代码.注意^并且$在正则表达式(sed用于匹配)中具有特殊含义,并且字面意思分别表示"在行的开头"和"在行的末尾".因此,除非转义,否则将忽略这些字符.因此,

echo "this and that" | sed 's/this$/cat/'

将保持字符串不变,因为你告诉sed在行的末尾寻找'this' - 因为'that'在结尾处,它不匹配.然而,

echo "It costs $50.00." | sed 's/\$50\.00/47.00 Swiss Francs/'

将按预期更改行,因为它$已被转义.对于二进制数据,只需在正则表达式部分之前包含\字符(\x5c)的十六进制代码\x24,它应该可以正常工作.

干杯.


Sad*_*ida 1

sed 语句应该如下所示

sed 's/\x15\x42\x02/\x12\x12\x02/g' test > test1
Run Code Online (Sandbox Code Playgroud)

它们应该位于搜索模式和应该替换它的模式之间

结果应该如下所示

[root@localhost ~]# cat test test1 | xxd -c 6       
0000000: 8f15 4202 24c2  ..B.$.
0000006: 8f12 1202 24c2  ....$.
Run Code Online (Sandbox Code Playgroud)