如何通过看起来像文本的二进制文件grep?

我有二进制文件,应该是文本(他们是导出日志),但我不能打开它less(它看起来很丑 – 它看起来像一个二进制文件)。 我发现我可以用vi打开它,而且我可以捕获它(你会看到实际的日志),但是我真正想做的是grep通过它们(不必用vi打开每一个,然后执行search)。 有没有办法做到这一点?

你可以使用grep来search文件 – 它并不关心input文件是否真的是文本。 从'man grep':

  -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If the first few bytes of a file indicate that the file contains binary data, assume that the file is of type TYPE. By default, TYPE is binary, and grep normally outputs either a one-line message saying that a binary file matches, or no message if there is no match. If TYPE is without-match, grep assumes that a binary file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. Warning: grep --binary-files=text might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. 

请在第二段末尾注明谨慎的词语。 您可能希望将结果从grepredirect到一个新文件,并用vi / less来检查。

通过stringspipe道,这将删除所有的二进制代码,只留下文本。

bgrep一试。 ( 原始版本 / 更新近的分支 )

你可以使用我认为的三个命令:

1) grep -a <sth> file.txt

2) cat -v file.txt | grep <sth> cat -v file.txt | grep <sth>

3) cat file.txt | tr '[\000-\011\013-\037\177-\377]' '.' | grep <sth> cat file.txt | tr '[\000-\011\013-\037\177-\377]' '.' | grep <sth>

从Grep 2.21开始,二进制文件的处理方式不同 :

当search二进制数据时,grep现在可以将非文本字节视为行终止符。 这可以显着提升性能。

那么现在发生的事情是,对于二进制数据,所有非文本字节(包括换行符)被视为行终止符。 如果你想改变这种行为,你可以:

  • 使用--text 。 这将确保只有换行符是行终止符

  • 使用--null-data 。 这将确保只有空字节是行终止符