Finding files which contain a certain string using find (1) and grep (1)

Solution 1:

That's because you're feeding grep a stream of text which just happens to contain filenames. Since you provided no filenames as arguments to grep, it cannot be expected to deduce what file a matched line came from. Use xargs:

find . -type f -print | xargs grep "some string"

Since you have GNU find/xargs, this is a safer way for xargs to read filenames:

find . -type f -print0 | xargs -0 grep "some string"

If you only want the filenames that have a matching line without showing the matching line:

find . -type f -print0 | xargs -0 grep -l "some string"

Solution 2:

I use

grep "some string" . -R

and it working faster

p.s.

More complex use case

grep -HiRE "some string|other string" . #H for file printing, i for case-insensitive, R for recursive search, E for regex 

To read param i explanation

grep --help | grep -- -i