如何在 Linux 上使用 grep 仅显示文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6637882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use grep to show just filenames on Linux?
提问by cwd
How can I use grep
to show just file-names (no in-line matches) on Linux?
如何grep
在 Linux 上仅显示文件名(无内联匹配)?
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
? I didn't see a way to do this on my grep
man page.
我怎样才能获得文件名(带路径),但没有匹配项?我必须使用xargs
吗?我在grep
手册页上没有看到执行此操作的方法。
采纳答案by Random832
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
在这种情况下你也不需要。
回答by Ignacio Vazquez-Abrams
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.)
-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.)
回答by Random832
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. Of course, if you need to select files on some other parameter, find is the correct solution:
所有的搜索都是由grep完成的。当然,如果您需要在其他参数上选择文件, 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 命令,并将文件名连接成一个命令 ( +
)。
回答by apl
Your question How can I just get the file-names (with paths)
你的问题我怎样才能得到文件名(带路径)
Your syntax example find . -iname "*php" -exec grep -H myString {} \;
您的语法示例find 。-iname "*php" -exec grep -H myString {} \;
My Command suggestion
我的命令建议
sudo find /home -name *.php
The output from this command on my Linux OS:
此命令在我的 Linux 操作系统上的输出:
compose-sample-3/html/mail/contact_me.php
compose-sample-3/html/mail/contact_me.php
As you require the filename with path, enjoy!
当您需要带路径的文件名时,请尽情享受!