如何使用grep在Linux上显示文件名?

本文介绍了如何在Linux环境中使用grep命令只显示文件名而无内联匹配。通常,结合使用grep的特定选项可以实现这一目标,如`-l`或`--files-with-matches`。在某些场景下,若需要根据其他参数选择文件,find命令可能是更好的选择。此外,还提到了grep手册页中关于`-l`选项的说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:How can I use grep to show just filenames on Linux?

How can I use grep to show just file-names (no in-line matches) on Linux? 如何在Linux上使用grep来显示文件名(没有内联匹配)?

I am usually using something like: 我通常使用类似的东西:

find . -iname "*php" -exec grep -H myString {} \;

How can I just get the file-names (with paths), but without the matches? 我怎样才能获得文件名(带路径),但没有匹配? Do I have to use xargs ? 我必须使用xargs吗? I didn't see a way to do this on my grep man page. 我没有在grep手册页上看到这样做的方法。


#1楼

参考:https://stackoom.com/question/Rqoc/如何使用grep在Linux上显示文件名


#2楼

For a simple file search you could use grep's -l and -r options: 对于简单的文件搜索,您可以使用grep的-l-r选项:

grep -rl "mystring"

All the search is done by grep. 所有的搜索都是由grep完成的。 Of course, if you need to select files on some other parameter, find is the correct solution: 当然,如果您需要在其他参数上选择文件,find是正确的解决方案:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command ( + ). execdir选项为每个目录构建每个grep命令,并将文件名连接到一个命令( + )。


#3楼

From the grep(1) man page: grep(1)手册页:

  -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by POSIX.) 

#4楼

The standard option grep -l (that is a lowercase L) could do this. 标准选项grep -l (即小写L)可以执行此操作。

From the Unix standard : Unix标准

-l
    (The letter ell.) Write only the names of files containing selected
    lines to standard output. Pathnames are written once per file searched.
    If the standard input is searched, a pathname of (standard input) will
    be written, in the POSIX locale. In other locales, standard input may be
    replaced by something more appropriate in those locales.

You also do not need -H in this case. 在这种情况下,您也不需要-H

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值