ChatGPT解决这个技术问题 Extra ChatGPT

grep 不显示路径/文件:行

你如何 grep 并且只返回匹配的行?即结果中省略了路径/文件名。

在这种情况下,我想查看当前目录中的所有 .bar 文件,搜索术语 FOO

find . -name '*.bar' -exec grep -Hn FOO {} \;

D
Dominic Rodger

无需find。如果您只是在特定目录中寻找模式,这应该足够了:

grep -hn FOO /your/path/*.bar

其中 -h 是隐藏文件名的参数,从 man grep 开始:

-h, --no-filename 禁止输出文件名的前缀。当只有一个文件(或只有标准输入)要搜索时,这是默认设置。

请注意,您正在使用

-H, --with-filename 打印每个匹配的文件名。当有多个文件要搜索时,这是默认设置。


行号可以省略吗?
@javadba 您可能正在使用别名,请输入 alias grep。要省略别名,请输入 \grep ...
是的,它使用了别名。
@javadba 省略 -n 标志
j
jkshah

只需将 -H 替换为 -h。查看 man grep 了解有关选项的更多详细信息

find . -name '*.bar' -exec grep -hn FOO {} \;

u
user229044

从手册页:

-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.