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' {} \;


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

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

   -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).

  • 4
    This answer could be improved by pointing out that the -H flag to grep is a nonstandard GNU extension and posing an alternative approach for non-GNU systems. – kojiro Oct 28 '12 at 3:43
find . -type f -exec grep -n 'string to search' /dev/null {} +

(or with GNU grep, see the -H option)


If your grep supports the recursive -r flag, this solves your request:

grep -rn "String to search " * 
  • 1
    That's true, but I don't see what this adds to the existing answers. – Wildcard Jul 18 '17 at 0:48
  • And if there’s only one (non-dot) file in the current directory, this doesn’t display the file’s name. – G-Man Oct 19 '17 at 23:56

protected by don_crissti Oct 19 '17 at 15:26

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.