如何将"find"与文件内特定信息的"grep"结合使用,并包括找到信息的文件名?



我非常熟悉使用与-exec一起使用,实际上它已成为我个人最喜欢的bash命令之一,因为它在视觉上看起来多么酷,而且功能强大和有用多么有用。

我需要在VPS上的某些文件中找到一个字符串,目录结构对我来说太大了,无法手动浏览并查找哪个文件包含该字符串,因此我认为它是查找的完美工作 - exec grep。

我拥有的命令的完整语法如下:

find ./ -type f -name "*.*" -exec grep "section for more information." {} ;

...这对于确认该字符串实际上在某些文件中发现了……但是哪个呢?我很想知道是否有语法显示文件包含字符串,最好是通往它们的完整路径,尽管我猜这不是强制性的。

预先感谢!

posix grep仅在指定多个文件名时才输出文件名。因此,典型的技巧是添加/dev/null,以确保总是超过1:

find ./ -type f -name "*.*" -exec grep "for more information." /dev/null {} ;

gnu和busybox grep s还具有-H,您可以使用:

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

另外,如果您不在乎匹配的行本身,而只想要文件名:

find ./ -type f -name "*.*" -exec grep -q "for more information." {} ; -print

不确定为什么要接受上述答案,因为它似乎无法解决您的原始询问,但这实际上是有效的。

find . -type f | while read f;do grep -q "for more information." $f && echo $f || true;done

最新更新