Monday, October 25, 2010

exclude svn folder and backup files when grep recursively

grep is my good friend, I use it at least 50 times every day in my work. Usually I am using it to search the code base a lot. It's a great tool, better than any text search tool I have ever used.

A common issue when you search the code base is the svn folder or backup files shows up as well as the result you are interested in.

A solution I used before is to pipe the result into another grep and use -v to filter out svn results, like following :

grep -R pattern path/to/search/ |grep -v svn
It works fine, but have two issues, it scan all svn folders  (usually it's a not problem, but if you have huge code base like me to work on, it's a pain), secondly, it ruins the wonderful colour highlight grep give to us as a free gift.

A better solution would be using the 'exclude' and 'exclude-dir' options from grep, like following :

grep --exclude-dir=\.svn --exclude=\*~ pattern path/to/search/ -Rn

It's fantastic,  it exclude all .svn folders, and also exclude all files ended '~' (some editor use it a backup file), and it also keep the colour highlighted result.

One step further, I added it to the .bashrc file, so it becomes the default setting and I don't need to type that much :

export GREP_OPTIONS="--exclude-dir=\.svn --exclude=\*~"

Bingo,  that's a perfect solution in my mind.

1 comment:

  1. $ grep --exclude-dir=\.svn --exclude=\*~ pattern path/to/search/ -Rn
    grep: unrecognized option '--exclude-dir=.svn'

    grep -V
    grep (GNU grep) 2.5.1

    it seems that there is no such option