我在目录树中寻找字符串foo=在文本文件中。在一个普通的Linux机器上,我有bash shell:

grep -ircl "foo=" *

目录中还有许多匹配“foo=”的二进制文件。由于这些结果不相关并降低了搜索速度,所以我希望grep跳过搜索这些文件(主要是JPEG和PNG图像)。我该怎么做呢?

我知道有——exclude=PATTERN和——include=PATTERN选项,但模式格式是什么?grep的手册页说:

--include=PATTERN     Recurse in directories only searching file matching PATTERN.
--exclude=PATTERN     Recurse in directories skip file matching PATTERN.

搜索grep包括,grep包括排除,grep排除和变体没有找到任何相关的

如果有更好的方法只在某些文件中进行grepping,我完全赞成;移动有问题的文件是行不通的。我不能只搜索某些目录(目录结构很混乱,到处都是东西)。此外,我不能安装任何东西,所以我必须使用常用工具(如grep或建议的find)。


当前回答

建议的命令:

grep -Ir --exclude="*\.svn*" "pattern" *

在概念上是错误的,因为——exclude作用于basename。换句话说,它将只跳过当前目录中的.svn。

其他回答

试试这个:

在currdir ..下创建一个名为“——F”的文件夹。(或链接另一个文件夹重命名为“-F”,即双减F。 #> grep -i——exclude-dir="\-\- f " "pattern" * .

在CentOS 6.6/Grep 2.6.3上,我必须这样使用它:

grep "term" -Hnir --include \*.php --exclude-dir "*excluded_dir*"

注意缺少等号“=”(否则——include,——exclude, include-dir和——exclude-dir将被忽略)

Find和xargs是你的朋友。使用它们来过滤文件列表,而不是grep的——exclude

试试这样的方法

find . -not -name '*.png' -o -type f -print | xargs grep -icl "foo="

习惯这一点的好处是,它可以扩展到其他用例,例如计算所有非png文件中的行数:

find . -not -name '*.png' -o -type f -print | xargs wc -l

删除所有非png文件。

find . -not -name '*.png' -o -type f -print | xargs rm

etc.

正如评论中指出的,如果某些文件的名称中可能有空格,请使用-print0和xargs -0代替。

适用于TCSH .alias文件:

alias gisrc 'grep -I -r -i --exclude="*\.svn*" --include="*\."{mm,m,h,cc,c} \!* *'

花了我一段时间才弄清楚{mm,m,h,cc,c}部分不应该在引号内。 ~基斯

我发现grepping grep的输出有时非常有用:

grep -rn "foo=" . | grep -v "Binary file"

不过,这实际上并没有阻止它搜索二进制文件。