Automatically ignore files in grep

2020-02-26 00:22发布

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 -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 bash
6条回答
来,给爷笑一个
2楼-- · 2020-02-26 00:49
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.

查看更多
Bombasti
3楼-- · 2020-02-26 00:50

--exclude option on grep will also work:

grep  perl * --exclude=try* --exclude=tk*

This searches for perl in files in the current directory excluding files beginning with try or tk.

查看更多
Emotional °昔
4楼-- · 2020-02-26 00:52

Use shell expansion

shopt -s extglob
for file in !(file1_ignore|file2_ignore) 
do
  grep ..... "$file"
done
查看更多
爷的心禁止访问
5楼-- · 2020-02-26 01:00

You might also want to take a look at ack which, among many other features, by default does not search VCS directories like .svn and .git.

查看更多
【Aperson】
6楼-- · 2020-02-26 01:05

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:

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.

after reading next post, apparently grep does have filename filtering.

查看更多
来,给爷笑一个
7楼-- · 2020-02-26 01:10

Here's a minimalistic version of .gitignore. Requires standard utils: awk, sed (because my awk is so lame), 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

grepignore builds a simple alternation clause:

egrep -v ignorefile_one|ignorefile_two

not incredibly efficient, but good for manual use

查看更多
登录 后发表回答