如果一行包含字符串,则 Grep 保留(输出)整个 .txt 文件

Use*_*ple 5 grep cygwin text-processing files

我知道

grep -rhI "# Active" > out.txt 
Run Code Online (Sandbox Code Playgroud)

将输出包含# Active在搜索目录中的任何行,但我想要整个 .txt 文件内容,例如

例子.txt

Line1 
Line2
Line3 # Active
Line4
Line5
etc
Run Code Online (Sandbox Code Playgroud)

因此,如果我 grep for# Active我希望它不仅输出包含# Active在这些 .txt 文件中的行,还输出所有其他行,例如

输出.txt

Line1 
Line2
Line3 # Active
Line4
Line5
etc
Run Code Online (Sandbox Code Playgroud)

B L*_*yer 12

对于grep不太可能有 的 的非 GNU 版本-z,或者如果需要可移植性...

grep -q pattern file && cat file
Run Code Online (Sandbox Code Playgroud)

-q抑制任何输出,但通常情况下,退出状态是根据是否找到模式匹配来设置的。使用模式匹配grep返回成功代码0,它等效于true并允许执行cat命令。


Joh*_*024 9

通常,grep 只会显示匹配的行:

$ grep -rhI "# Active"
Line3 # Active
Run Code Online (Sandbox Code Playgroud)

要查看整个文件,请添加-z标志:

$ grep -rhIz "# Active"
Line1 
Line2
Line3 # Active
Line4
Line5
etc
Run Code Online (Sandbox Code Playgroud)

-z是一个 GNU 扩展,它告诉 grep 不要使用换行符作为“行”分隔符,而是使用 NUL 字符。由于文本文件中通常没有 NUL 字符,这会告诉 grep 读取整个文件,就好像它是单个“行”一样。因此,如果匹配,则打印整个文件。

在 BSD/OSX 版本的 grep 上,NUL 输入选项不可用并且-z表示其他含义。

其他 grep 选项

-r 告诉 grep 递归搜索文件和目录。

-I 告诉 grep 忽略二进制文件

-h 告诉 grep 在不附加文件名的情况下打印匹配项。