grep – 列出找到匹配项的文件名

我在目录中有一堆.html文件。 我想查看每个文件并匹配一个模式(MD5)。 所有这一切都很容易。 问题是我需要知道找到匹配项的文件。

cat *.html | grep 75447A831E943724DD2DE9959E72EE31 

仅返回找到匹配项的HTML页面内容,但它不会告诉我找到它的文件。如何让grep向我显示找到匹配项的文件名?

 grep -H 75447A831E943724DD2DE9959E72EE31 *.html 

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

我一直用这个来查找包含字符串的文件,目录中的RECURSIVELY(表示遍历任何子子文件夹) grep -Ril "yoursearchtermhere"

  • R是递归搜索(遵循符号链接)
  • i是让它不区分大小写
  • l只是列出文件的名称。

所以回答你的问题grep -l '75447A831E943724DD2DE9959E72EE31' *.html会做但你可以做grep -Ril '75447A831E943724DD2DE9959E72EE31'在任何子文件夹的任何文件中查找该字符串,不区分大小写

你可以试试这个

 grep -rl '75447A831E943724DD2DE9959E72EE31' * > found.txt 
 grep -r -H 75447A831E943724DD2DE9959E72EE31 *.html | awk -F : ' { print $1 } ' 

替代

 grep -r -l 75447A831E943724DD2DE9959E72EE31 *.html 

以上操作将在文件夹和子文件夹中递归搜索并打印文件的路径…

Cyrus发布的答案是绝对正确的,如果我们只需要查找文件,那么使用grep来做正确的方法TM 。 当文件名需要对匹配的文件名进行额外的解析或操作时,我们可以使用带有if语句的while循环。 下面是一个示例,其中文件名列表来自非常常用的find + while结构,用于安全地解析文件名。

 find -type f -name "*.html" -print0 | while IFS= read -r -d '' filename do if grep -q 'PATTERN' "$filename" then printf "%s found in %s\n" 'PATTERN' "$filename" # Here we can insert another command or function # to perform other operations on the filename fi done