Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 19 down vote accepted

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

share|improve this answer
thank you, that worked! – Danny_Joris Oct 27 '12 at 21:17
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)

share|improve this answer
both + and -H work great, thank you! – Danny_Joris Oct 27 '12 at 21:17
And related to this answer: unix.stackexchange.com/questions/3682/… – Danny_Joris Oct 28 '12 at 1:42
+1 Right, because causing grep to have multiple filename args would force it to output the matched filenames. Clever! – kojiro Oct 28 '12 at 3:47

IMO, grep -r works best.

for instance, you want to search for the number 7546899 in a bunch of files:

grep -r 7546899

it will show something like:

<filename where is found the >:<something something>7546899<moretext>
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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