我在目录树中寻找字符串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 --exclude="*\.svn*" -rn "foo=" * | grep -v Binary | grep -v tags

其他回答

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

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

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

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

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

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

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

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

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

试试这个:

 $ 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

试试这个:

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