Bookmark and Share

Customizing grep tool to exclude svn.

Posted: Wednesday, February 4th, 2009 at 10:00 pmUpdated: Friday, April 3rd, 2009 at 5:12 pm

I mostly do programming by SSH-ing to development server. The code I’m working on are often managed by using SVN. There are many occasions when I need to search all source code to find a particular string. If you’ve worked on a source code that’s managed by SVN before, you’ll pretty soon notice that there are many entries under .svn directory that’s just cluttering the result. So what I needed is to find a way to do grep but excludes some files that I know I don’t need.

The first option that I came up with was to write a wrapper shell script called mygrep. I normally put it on bin directory under my home directory (~/bin) as this path are often on your search path for a command.

#!/bin/sh

if [ $# = 1 ]
then
   grep -iR "$1" * | grep -v "\.svn\/"
elif [ $# = 2 ]
then
   grep -iR "$1" $2/* | grep -v "\.svn\/"
else
   echo "Too many parameters"
fi

The shell script above is basically checking if you are passing 1 or 2 parameters. It basically executes grep command recursively on a directory searching for a specified string in non case sensitive way. After that, you pipe the output to another grep that will exclude all lines with .svn on it. If you need to exclude more files, etc, just chain the command grep -v with more criteria. Once you save it under bin directory on your home directory, you can simply call it like this.

user@laptop:~$ mygrep "one two"

Another possible solution (thanks to my friend Jamsa) is to use grep’s option –exclude-dir. You can chain it with more dirs to exclude. In that case, you may not need to create a separate shell script. Just create an alias of grep to grep –exlclude-dir=".svn". In that case, here’s what you do

user@laptop:~$ alias mygrep="grep -ir --exclude-dir='.svn' $@"
user@laptop:~$ mygrep "one two"

Note that –exclude-dir exists from grep version 2.5.3 onwards. Do grep -V to find out what version currently installed in yours. If you have less than 2.5.3, then perhaps my original way is the only way to do this.

So there you have it. As always, I welcome comments / questions / critics that will help me and other readers understand better.

Leave a Reply