我在目录树中寻找字符串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)。


当前回答

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

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

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

其他回答

看这个。

grep --exclude="*\.svn*" -rn "foo=" * | grep -v Binary | grep -v tags

这些脚本并不能解决所有的问题……试试这个吧:

du -ha | grep -i -o "\./.*" | grep -v "\.svn\|another_file\|another_folder" | xargs grep -i -n "$1"

这个脚本非常好,因为它使用“真正的”正则表达式来避免目录搜索。只需在grep -v上用“\|”分隔文件夹或文件名即可

享受它! 在我的Linux shell上找到!XD

GNU grep的——binary-files=without-match选项使其跳过二进制文件。(相当于其他地方提到的-I开关。)

(这可能需要最新版本的grep;至少2.5.3版本有。)

试试这个:

 $ find . -name "*.txt" -type f -print | xargs file | grep "foo=" | cut -d: -f1

创立于:http://www.unix.com/shell-programming-scripting/42573-search-files-excluding-binary-files.html

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代替。