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

本文翻译自: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

发布了0 篇原创文章 · 获赞 137 · 访问量 84万+

猜你喜欢

转载自blog.csdn.net/xfxf996/article/details/105326067