Sunday, October 24, 2021

[SOLVED] How to know which file holds grep result?

Issue

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?


Solution

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 {} +


Answered By - Frank Schmitt