为什么二进制文件上的 grep -P 有时会匹配错误的字节?
Why does grep -P on binary files sometimes match wrong bytes?
我正在尝试使用 grep -P
在可能很大的二进制文件中查找特定的字节序列。然而,它有时会匹配它不应该匹配的地方 - 例如,这是一个打高尔夫球的案例,它似乎只是 "match over" 一个错误的 \xc2
字节:
➜ alias bin2hex='xargs echo -n | od -An -tx1'
➜ echo -e '\x3e\x1f\xc2\x9d\xa0' > test.bin
➜ cat test.bin | bin2hex
3e 1f c2 9d a0
➜ grep -P '\x1f\x9d' test.bin
Binary file test.bin matches
➜ grep -Pao '\x1f\x9d' test.bin | bin2hex
1f c2 9d
为什么会这样?
可以避免吗?
这个命令:
grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0') | xargs echo -n | od -An -tx1
不打印任何 grep
版本:
- GNU grep 2.5.1
- GNU grep 2.6.3
- GNU grep 2.21
您确定您的 grep
没有任何错误的别名 (type grep
) 吗?
更新:将评论转换为答案
我可以用不同的 LANG
值重现您的问题:
LANG=en_US.UTF-8; grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0')
Binary file (standard input) matches
问题没有重现:
LANG=en_US; grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0')
我正在尝试使用 grep -P
在可能很大的二进制文件中查找特定的字节序列。然而,它有时会匹配它不应该匹配的地方 - 例如,这是一个打高尔夫球的案例,它似乎只是 "match over" 一个错误的 \xc2
字节:
➜ alias bin2hex='xargs echo -n | od -An -tx1'
➜ echo -e '\x3e\x1f\xc2\x9d\xa0' > test.bin
➜ cat test.bin | bin2hex
3e 1f c2 9d a0
➜ grep -P '\x1f\x9d' test.bin
Binary file test.bin matches
➜ grep -Pao '\x1f\x9d' test.bin | bin2hex
1f c2 9d
为什么会这样?
可以避免吗?
这个命令:
grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0') | xargs echo -n | od -An -tx1
不打印任何 grep
版本:
- GNU grep 2.5.1
- GNU grep 2.6.3
- GNU grep 2.21
您确定您的 grep
没有任何错误的别名 (type grep
) 吗?
更新:将评论转换为答案
我可以用不同的 LANG
值重现您的问题:
LANG=en_US.UTF-8; grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0')
Binary file (standard input) matches
问题没有重现:
LANG=en_US; grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0')