Take the 2-minute tour ×
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

2 Answers 2

up vote 8 down vote accepted

The command line switch -H forces grep to print the line number, 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.
share|improve this answer
    
thank you, that worked! –  Danny_Joris Oct 27 '12 at 21:17
1  
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  
+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

Your Answer

 
discard

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.