如何使用grep仅返回匹配的行?即结果中省略路径/文件名。
在这种情况下,我想在当前目录中查找所有.bar文件,搜索术语FOO。
find . -name '*.bar' -exec grep -Hn FOO {} \;
无需 find
。 如果您只是在特定目录中寻找模式,那么这应该就足够了:
grep -hn FOO /your/path/*.bar
-h
是一个参数,用于在输出结果时隐藏文件名,根据 man grep
的说明:
-h, --no-filename
在输出结果时省略文件名前缀。当只有一个文件(或只有标准输入)需要被搜索时,这是默认行为。
请注意,你原本使用的是:
-H, --with-filename
对于每个匹配项,打印该项所在的文件名。当需要搜索多个文件时,这是默认行为。
只需将-H
替换为-h
。有关选项的更多详细信息,请参阅man grep
。
find . -name '*.bar' -exec grep -hn FOO {} \;
以下是man手册中的内容:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there
is only one file (or only standard input) to search.
alias grep
查看。如果要忽略别名,请输入\grep ...
。 - fedorqui