Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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

3 Answers 3

up vote 12 down vote accepted

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

% grep -n 7
% grep -Hn 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).

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:… –  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.