Grep – How to Return File Name and Line Number with Find -exec

findgrep

When using find, how do I return the file name and the line number when searching for a string? I manage to return the file name in one command and the line numbers with another one, but I can't seem to combine them.

File names: find . -type f -exec grep -l 'string to search' {} \;

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

Best Answer

The command line switch -H forces grep to print the file name, even with just one file.

% grep -n 7 test.in
7:7
% grep -Hn 7 test.in
test.in:7:7

   -H, --with-filename
          Print the filename for each match.

Note that as Kojiro says in a comment, this is not part of the POSIX standard; it is in both GNU and BSD grep, but it's possible some systems don't have it (e.g. Solaris).

Related Question