How to return both file name and line number with find … -exec grep?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

find . -type f -exec grep -n 'string to search' /dev/null {} +

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

Method 3

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

grep -rn "String to search " *


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x