我需要计算0xFF 0x84 0x03 0x07
二进制文件中十六进制字符串的出现次数,没有太多麻烦......有没有一种从linux命令行快速获取这些数据的方法,或者我应该编写专门的代码来做到这一点?
5 回答
如果您的版本grep
采用-P
参数,那么您可以使用grep -a -P
, 在二进制文件中搜索任意二进制字符串。这接近你想要的:
grep -a -c -P '\xFF\x84\x03\x07' myfile.bin
-a
确保不会跳过二进制文件-c
输出计数-P
指定您的模式是与 Perl 兼容的正则表达式 (PCRE),它允许字符串包含上述\xNN
格式的十六进制字符。
不幸的是,grep -c
只会计算模式出现的“行”数 - 而不是实际出现的次数。
要获得 的确切出现次数grep
,您似乎需要执行以下操作:
grep -a -o -P '\xFF\x84\x03\x07' myfile.bin | wc -l
grep -o
将每个匹配项分开到自己的行中,并wc -l
计算行数。
请注意,这一切都取决于您的二进制字符串不包含换行符这一事实。
如果您确实需要使用此方法 grep 换行符,我能想到的最简单的方法是tr
将字符交换为不在您的搜索词中的另一个字符。
# set up test file (0a is newline)
xxd -r <<< '0:08 09 0a 0b 0c 0a 0b 0c' > test.bin
# grep for '\xa\xb\xc' doesn't work
grep -a -o -P '\xa\xb\xc' test.bin | wc -l
# swap newline with oct 42 and grep for that
tr '\n\042' '\042\n' < test.bin | grep -a -o -P '\042\xb\xc' | wc -l
像使用 hexdump
hexdump -v -e '"0x" 1/1 "%02X" " "' <filename> | grep -oh "0xFF 0x84 0x03 0x07" |wc -w
hexdump
将以给定格式输出二进制文件,如 0xNN
grep
将找到所有出现的字符串,而不考虑在一行上重复的相同字符串
wc
会给你最后的计数
How about:
$ hexdump a.out | grep -Ec 'ff ?84 ?03 ?07'
你试过了grep -a
吗?
来自 grep 手册页:
-a, --text
Process a binary file as if it were text; this is equivalent to the --binary-files=text option.
This doesn't quite answer your question, but does solve the problem when the search string is ASCII but the file is binary:
cat binaryfile | sed 's/SearchString/SearchString\n/g' | grep -c SearchString
Basically, 'grep' was almost there except it only counted one occurrence if there was no newline byte in between, so I added the newline bytes.