6

我需要计算0xFF 0x84 0x03 0x07二进制文件中十六进制字符串的出现次数,没有太多麻烦......有没有一种从linux命令行快速获取这些数据的方法,或者我应该编写专门的代码来做到这一点?

4

5 回答 5

4

如果您的版本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
于 2016-05-30T23:01:44.080 回答
1

像使用 hexdump

hexdump -v -e '"0x" 1/1 "%02X" " "' <filename> | grep -oh "0xFF 0x84 0x03 0x07" |wc -w

hexdump将以给定格式输出二进制文件,如 0xNN

grep将找到所有出现的字符串,而不考虑在一行上重复的相同字符串

wc会给你最后的计数

于 2013-03-11T10:46:02.170 回答
0

How about:

$ hexdump a.out | grep -Ec 'ff ?84 ?03 ?07'
于 2013-03-11T11:24:59.187 回答
0

你试过了grep -a吗?

来自 grep 手册页:

-a, --text
              Process a binary file as if it were text; this is equivalent to the --binary-files=text option.
于 2013-03-11T10:38:47.720 回答
0

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.

于 2013-08-14T16:49:17.213 回答