如何使用 find ... -exec grep 返回文件名和行号?

Dan*_*ris 55 grep find

使用时find,如何在搜索字符串时返回文件名和行号?我设法在一个命令中返回文件名,并用另一个命令返回行号,但我似乎无法将它们组合起来。

文件名: find . -type f -exec grep -l 'string to search' {} \;

行号: find . -type f -exec grep -n 'string to search' {} \;

Kev*_*vin 63

命令行开关-H强制grep打印文件名,即使只有一个文件。

% grep -n 7 test.in
7:7
% grep -Hn 7 test.in
test.in:7:7
Run Code Online (Sandbox Code Playgroud)
   -H, --with-filename
          Print the filename for each match.
Run Code Online (Sandbox Code Playgroud)

请注意,正如Kojiro评论中所说,这不是 POSIX 标准的一部分;它在 GNU 和 BSD grep 中都有,但可能有些系统没有它(例如 Solaris)。

  • 可以通过指出`grep` 的`-H` 标志是一个[非标准GNU 扩展](http://pubs.opengroup.org/onlinepubs/009695399/utilities/grep.html) 并提出一个非 GNU 系统的替代方法。 (4认同)

Sté*_*las 25

find . -type f -exec grep -n 'string to search' /dev/null {} +
Run Code Online (Sandbox Code Playgroud)

(或使用 GNU grep,请参阅-H选项)

  • +1 是的,因为导致 `grep` 有多个文件名参数会迫使它输出匹配的文件名。聪明的! (4认同)