Friday, September 28, 2012

Searching Files with bash, find, and grep

I often find myself in the situation where I am working in a deeply nested project, and need to search all of the source files for a keyword. One solution is to pipe together the find and grep commands. For instance, one could invoke

find . -type f -name "*.c" -print | xargs grep -rn printf
to find all occurrences of the printf function. For ease of use, I decided to wrap this functionality in a bash script.

findgrep.sh


#!/bin/sh

usage() {
    prog=`basename $0`
    cat << EOF

    usage $prog [-d ROOT_DIR] [-s] FILE KEYWORD

    Options:
        -d ROOT_DIR     root directory to start the search from
        -s              case sensentive search     

    Search for all files under ROOTDIR directory with a name matching
    FILE pattern.  Among the files found, grep for the KEYWORD pattern.

    Examples:

        # search for C source files under /home/joe that mention 'socket'
        $prog -d /home/joe "*.c" socket

        # search for use of 'synchronized' keyword in all Java source files
        # under the current working directory
        $prog -s "*.java" synchronized 

EOF
}


findgrep() {
    if [[ $4 -eq 0 ]]
    then
        grep_args="-in"
    else
        grep_args="-n"
    fi
    find "$1" -type f -name "$2" -print | xargs grep $grep_args "$3"
}

root_dir=`pwd`
case_sensitive=0

while getopts ":hd:s" option
do
    case $option in
    h)
        usage
        exit 1
        ;;
    d)
        rood_dir=$OPTARG
        ;;
    s)
        case_sensitive=1
        ;;
    \?)
        echo "invalid option: -$OPTARG" >&2
        exit
        ;;
    esac
done


# shift command line arguments so that first positional argument is $1
shift $((OPTIND-1))

if [[ $# -ne 2 ]]
 then
    usage
    exit 1
fi

findgrep $root_dir $1 $2 $case_sensitive                                                             
Example:
$ pwd
/Users/smherwig/github
$ ls
lua-daemon  lua-mnt     lua-proc    pytk-editor
$ findgrep.sh -s "*.c" statvfs
/Users/smherwig/github/lua-mnt/src/mnt.c:7:#include <sys/statvfs.h>;
/Users/smherwig/github/lua-mnt/src/mnt.c:154:    struct statvfs  sbuf;
/Users/smherwig/github/lua-mnt/src/mnt.c:157:    ret = statvfs(path, &sbuf);

No comments:

Post a Comment