Saturday, August 07, 2010

Linux BASH function to search recursively for a string in all files in the current directory

If you do any serious coding at all, you would have used a "Search" function in your editor. Some IDEs even allow you to search within the entire project/workspace or a subset of files within that workspace. But when you are using a simple text editor that does not support such features, such functionality is sorely missed.

Fortunately, the Linux shell BASH provides an easy way to search for any string recursively in a directory. Just cd to the desired location and do -
grep -ri "[a phrase]" .
This would give you the results of a recursive (-r), case insensitive match (-i) for the supplied string in all the files in the current directory.

But I find even this small line a pain to type when I have to do this every other minute during a marathon coding session. So I wrote a small wrapper function to make this even easier -

function grepcr() {
if [ $# -gt 0 ]; then
a=$1
shift
fi
sp=" "
while [ $# -gt 0 ]; do
a=$a$sp$1
shift
done
echo "grep -ri \"$a\" ."
grep -ri "$a" .
}

Just put this function in your ~/.bashrc file and then you can search for "a phrase" using the simple -
grepcr a phrase
As you may have guessed, "grepcr" stands for GREP Contents Recursively.


1 comment:

jordi said...

Useful, thanks !!