我构建了一个grep命令,用来递归搜索一个文件目录中的模式。问题是grep只返回模式所在的文件名,而不是模式的精确匹配。我如何返回实际结果?
例子
文件名 somefile.bin
包含 somestring0987654321�123�45�
在一个有无数其他文件的目录中
命令:
$ grep -EsniR -A 1 -B 1 '([a-zA-Z0-9]+)\x00([0-9]+)\x00([0-9]+)\x00' *
当前结果:
Binary file somefile.bin matches
所需的结果(或与之接近)。
Binary file somefile.bin matches
<line above match>
somestring0987654321�123�45�
<line below match>
你可以试试 -a
选项。
File and Directory Selection
-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.
但问题是,在二进制文件中 纹丝不动所以我不知道你想要的输出是什么样子的。你会看到随机的垃圾,也许是整个文件,一些特殊的字符搞得你的终端可能会被打印出来。
如果你想把输出限制在比赛本身,可以考虑使用 -o
选项。
-o, --only-matching
Print only the matched (non-empty) parts of a matching line,
with each such part on a separate output line.
上下文控制仅限于添加一定数量的...。行 在匹配之前或之后,这在这里可能不会有很好的效果。所以,如果你想要一个特定字节数的上下文,你就必须改变模式本身。
试试...
grep -rnw "<regex>" <folder>
简单多了。更多的例子在这里--> https:/computingbro.com20200510word-search-in-linux-unix-filesystem(文件系统)