bash 自动忽略grep中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1892293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automatically ignore files in grep
提问by rampr
Is there any way I could use grep to ignore some files when searching something, something equivalent to svnignore or gitignore? I usually use something like this when searching source code.
有什么方法可以在搜索某些内容时使用 grep 忽略某些文件,例如 svnignore 或 gitignore?我在搜索源代码时通常使用这样的东西。
grep -r something * | grep -v ignore_file1 | grep -v ignore_file2
Even if I could set up an alias to grep to ignore these files would be good.
即使我可以为 grep 设置一个别名来忽略这些文件也会很好。
回答by ennuikiller
--excludeoption on grep will also work:
--excludegrep 上的选项也将起作用:
grep perl * --exclude=try* --exclude=tk*
This searches for perl in files in the current directory excluding files beginning with tryor tk.
这将在当前目录中的文件中搜索 perl,不包括以try或开头的文件tk。
回答by Ned Deily
回答by Ben Hayden
find . -path ./ignore -prune -o -exec grep -r something {} \;
What that does is find all files in your current directory excluding the directory (or file) named "ignore", then executes the command grep -r something on each file found in the non-ignored files.
它的作用是查找当前目录中的所有文件,不包括名为“ignore”的目录(或文件),然后在非忽略文件中找到的每个文件上执行命令 grep -r something。
回答by ghostdog74
Use shell expansion
使用外壳扩展
shopt -s extglob
for file in !(file1_ignore|file2_ignore)
do
grep ..... "$file"
done
回答by Anycorn
I thinks grep does not have filename filtering. To accomplish what you are trying to do, you can combine find, xargs, and grep commands. My memory is not good, so the example might not work:
我认为 grep 没有文件名过滤。要完成您要执行的操作,您可以组合使用 find、xargs 和 grep 命令。我的记性不好,所以这个例子可能不起作用:
find -name "foo" | xargs grep "pattern"
Find is flexible, you can use wildcards, ignore case, or use regular expressions. You may want to read manual pages for full description.
Find 很灵活,可以使用通配符、忽略大小写或使用正则表达式。您可能需要阅读手册页以获取完整说明。
after reading next post, apparently grep does have filename filtering.
阅读下一篇文章后,显然 grep 确实具有文件名过滤功能。
回答by zen
Here's a minimalistic version of .gitignore. Requires standard utils: awk, sed (because my awk is so lame), egrep:
这是 .gitignore 的简约版本。需要标准的 utils:awk、sed(因为我的 awk 太蹩脚了)、egrep:
cat > ~/bin/grepignore #or anywhere you like in your $PATH
egrep -v "`awk '1' ORS=\| .grepignore | sed -e 's/|$//g' ; echo`"
^D
chmod 755 ~/bin/grepignore
cat >> ./.grepignore #above set to look in cwd
ignorefile_1
...
^D
grep -r something * | grepignore
grepignorebuilds a simple alternation clause:
grepignore构建一个简单的替代子句:
egrep -v ignorefile_one|ignorefile_two
not incredibly efficient, but good for manual use
效率不高,但适合手动使用

