我有二进制文件,它们应该是文本(它们是导出的日志),但我无法用 less 打开它(它看起来很丑 - 它看起来像一个二进制文件)。我发现我可以用 vi 打开它,也可以 cat 它(你会看到实际的日志),但我真正想做的是 grep 浏览它们(而不必用 vi 打开每个文件然后执行搜索)。我有什么办法可以做到这一点吗?
答案1
您可以使用grep
anyway 来搜索文件 - 它并不关心输入文件是否真的是文本。来自“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.
请标记第二段末尾的警告字样。您可能希望将 grep 的结果重定向到新文件,并使用 vi / less 检查它。
答案2
通过管道strings
将其去除,所有二进制代码都只留下文本。
答案3
答案4
从 Grep 2.21 开始,二进制文件区别对待:
在搜索二进制数据时,grep 现在可以将非文本字节视为行终止符。这可以显著提高性能。
因此,现在的情况是,对于二进制数据,所有非文本字节(包括换行符)都被视为行终止符。如果要更改此行为,您可以:
使用
--text
。这将确保只有换行符是行终止符使用
--null-data
。这将确保只有空字节是行终止符