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

cwd*_*cwd 970 linux grep

如何grep在Linux上使用仅显示文件名(无内联匹配)?

我通常使用类似的东西:

find . -iname "*php" -exec grep -H myString {} \;
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得文件名(带路径),但没有匹配?我必须使用xargs吗?在我的grep手册页上,我没有看到这样做的方法.

Ran*_*832 1480

标准选项grep -l(即小写L)可以做到这一点.

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.
Run Code Online (Sandbox Code Playgroud)

-H在这种情况下你也不需要.

  • 这个选项的文档是(通常在大多数man文件中),所以不清楚!Pfff ......令人惊讶的是,男人可以成为一个痛苦的屁股. (28认同)
  • @Hauke 我的答案是-l。我提到 -H 只是因为问题中的用户命令包含 -H 并且给出 -l 时它是多余的。 (4认同)
  • 很好,我个人喜欢将它与其他标志 `grep -nrl "some text" .` 在一组子文件夹中递归查找文本时使用 (4认同)
  • -H 还显示匹配本身。问题只是针对文件名。 (2认同)
  • ell 的助记符是什么? (2认同)

Ign*_*ams 134

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.)
Run Code Online (Sandbox Code Playgroud)

  • @ IgnacioVazquez-Abrams完全正确.该文档的第一印象让您觉得它只会打印第一个文件的文件名.你真的需要一些阅读来理解它. (14认同)
  • 文档使它有点不清楚."扫描将在第一场比赛时停止" - 表示将打印所有文件名,但匹配单词的扫描将在第一次出现时停止. (7认同)
  • '当前文件的扫描将在第一场比赛时停止.会更清楚. (4认同)
  • 在第一场比赛停止是必要的和自然. (3认同)
  • @VishalP:由于我们不关心出现的位置,只关心它们存在,因此在第一次出现之后搜索每个文件是没有意义的。 (2认同)

小智 31

对于简单的文件搜索,您可以使用grep -l-r选项:

grep -rl "mystring"
Run Code Online (Sandbox Code Playgroud)

所有的搜索都是由grep完成的.当然,如果您需要在其他参数上选择文件,find是正确的解决方案:

find . -iname "*.php" -execdir grep -l "mystring" {} +
Run Code Online (Sandbox Code Playgroud)

execdir选项为每个目录构建每个grep命令,并将文件名连接到一个命令(+).