使用grep --exclude / - include语法不要浏览某些文件

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

grep -ircl "foo=" *

在目录中还有许多匹配“foo =”的二进制文件。 因为这些结果不相关而且减慢了搜索速度,我但愿grep跳过搜索这些文件(主要是JPEG和PNG图像)。 我该怎么办? bash

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

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

搜索grep includegrep include excludegrep exclude和variants没有找到任何相关内容 工具

若是有一种更好的方法只在某些文件中进行grepping,我就是尽心尽力; 移动违规文件不是一种选择。 我不能只搜索某些目录(目录结构很乱,随处可见)。 另外,我没法安装任何东西,因此我必须使用经常使用工具(如grep或建议的查找 )。 spa


#1楼

我是一个dilettante,授予,但这是个人〜/ .bash_profile看起来如何: 命令行

export GREP_OPTIONS="-orl --exclude-dir=.svn --exclude-dir=.cache --color=auto" GREP_COLOR='1;32'

请注意,要排除两个目录,我必须使用--exclude-dir两次。 code


#2楼

通过很长一段时间我发现了这个,你能够添加多个包含并排除以下: ip

grep "z-index" . --include=*.js --exclude=*js/lib/* --exclude=*.min.js

#3楼

使用shell globbing语法: 字符串

grep pattern -r --include=\*.{cpp,h} rootdir

--exclude的语法是相同的。 扩展

请注意,使用反斜杠转义星号以防止它被shell展开(引用它,例如--include="*.{cpp,h}" ,也能够正常工做)。 不然,若是当前工做目录中的任何文件与模式匹配,命令行将扩展为相似grep pattern -r --include=foo.cpp --include=bar.h rootdir ,它只会搜索文件名为foo.cppbar.h ,极可能不是你想要的。


#4楼

我发现grepping grep的输出有时很是有用:

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

虽然,这实际上并无阻止它搜索二进制文件。


#5楼

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

尝试相似的东西

find . -not -name '*.png' -o -type f -print | xargs grep -icl "foo="
相关文章
相关标签/搜索