Sunday, August 12, 2018

Searching for source files which contain multiple keywords

Recently I was presented with the challenge of searching for the code which built a SQL query.  I knew what the query looked like from a log file but searching for individual terms used in the query such as SELECT, FROM, or WHERE produced hundreds of matches which I didn't want to waste time checking one at a time.

So I created the following bash script to search files for each term in order.  I used ack instead of grep for the first search so it would pick only source files of interest for me.  The results from my bash script returned only a single file which contained all the terms and it was this one which I needed to modify.

if [ -z "$2" ]                       # Is parameter #1 zero length?
then
    echo "usage -- rgt term1 term2 [term3]..."
    exit 1
fi

files=`ack -l "$1"`


# shift past the first search term argument since 
# we've already used that one 
shift  

for var in "$@"
do
    files=`echo $files | xargs grep -l $var`
done

if [ -z "$files" ]; then    # are results zero length?
    echo "no matching files found"
else
    echo "matching files:"
    echo "-------------------------------------"
    echo "$files"
fi

No comments: