m.r226 m.r226 - 3 months ago 12
Linux Question

How to know which file holds grep result?

There is a directory which contains 100 text files. I used grep to search a given text in the directory as follow:

cat *.txt | grep Ya_Mahdi


and grep shows
Ya_Mahdi
.

I need to know which file holds the text. Is it possible?

Answer

Just get rid of cat and provide the list of files to grep:

grep Ya_Mahdi *.txt

While this would generally work, depending on the number of .txt files in that folder, the argument list for grep might get too large.

You can use find for a bullet proof solution:

find --maxdepth 1 -name '*.txt' -exec grep -H Ya_Mahdi {} +