Ubuntu – Grep showing file name and string found

grep

I need an egrep command that list all the file names that contains the words + which string it has found. Let's imagine this scenario:

Words that I need to find: apple, watermelon and banana.

What I need: I want to list all files that contains any of them (don't need to have all of them in the same file), and print which word it found in the file. Example of a search result I want:

./file1.txt:apple
./file1.txt:banana
./file2.txt:watermelon
./file5.txt:apple

I remember seeing a grep command which shows FILENAME:STRING in the search results, but I can't remember how it was done. I tried:

egrep -lr 'apple|banana|watermelon' .

But the search results showed:

./file1.txt
./file2.txt

Ok, it helps but … in file1, which one of the words it found? That's the problem I'm facing .

Best Answer

You used -l, which is the opposite of what you want. From man grep:

-l, --files-with-matches
      Suppress normal output; instead print the  name  of  each  input
      file  from  which  output would normally have been printed.  The
      scanning will stop on the first  match.   (-l  is  specified  by
      POSIX.)

What you want is -H:

-H, --with-filename
      Print the file name for each match.  This is  the  default  when
      there is more than one file to search.

But that's the default anyway. Just do:

grep -Er 'apple|banana|watermelon' .

(The -E tells grep to act like egrep.)