如何知道哪个文件包含grep结果?

时间:2022-12-20 19:35:46

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

有一个包含100个文本文件的目录。我使用grep搜索目录中的给定文本,如下所示:

cat *.txt | grep Ya_Mahdi

and grep shows Ya_Mahdi.

和grep显示Ya_Mahdi。

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

我需要知道哪个文件包含文本。可能吗?

1 个解决方案

#1


4  

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

只需摆脱cat并提供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.

虽然这通常有效,但根据该文件夹中.txt文件的数量,grep的参数列表可能会变得太大。

You can use find for a bullet proof solution:

您可以使用find作为防弹解决方案:

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

#1


4  

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

只需摆脱cat并提供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.

虽然这通常有效,但根据该文件夹中.txt文件的数量,grep的参数列表可能会变得太大。

You can use find for a bullet proof solution:

您可以使用find作为防弹解决方案:

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