Using find and grep to search files

By Eric Downing. Filed in Scripting, Shell, Utilities  |  
TOP del.icio.us digg

I have been searching through source code and files for years. And I used to use find with a few arguments to get what I was looking for.

find . -exec grep  {} ; -print

I used the -print after the exec arguments to show the file only when the grep succeeded.  This worked but was a bit to type each time I used it. So I came up with a little script that would help me to search for the an argument and even allow a case insensitive search as well.
 

#!/bin/sh

if [ $# -lt 1 ]; then
  echo 1>&2 Usage: $0 ""
  exit 127
fi
icase=
search=

while [ $# -ge 1 ]; do
  case $1 in 
     -i) icase=$1;;
      *) search=$1 ;;
  esac
  shift
done

find . -type f -print0 | xargs -0 grep $icase $search

The script takes at least one argument and excepts a ‘-i’ argument to make grep use a case insensitive search. This will print the file name and the line that matches the search term. It can be easily adapted to show the count of matched patterns (‘-c’) or the line number (‘-n’).

Tags: , , ,

Leave a Reply