Back to TechNotes
# Recursive grep
# This script accepts a search pattern and greps for that pattern
# in all text files within the current directory (and all subdirectories
# within it). It outputs a list of files containing the pattern,
# a list of directories searched, and the full grep output.
# It then allows you to vim the list of files containing the pattern
# or the files themselves.
#
# P.S. It might have been faster to use find to get the full list of
# files instead of cd'ing back and forth, but I like this because it
# starts searching right away and doesn't require building some mondo
# file list.
#
# Syntax: regrep <pattern>
# cd to top directory before running
#
if test "$1" = ""
then
echo "# Syntax: regrep <pattern>
(cd to top directory before running)"
exit
fi
# Initialize some variables
pattern="$1" # Searched for pattern
outfile=/tmp/out$$ # File saving grep output
dirfile=/tmp/dir$$ # File saving directories searched
filelist=/tmp/list$$ # File saving list of files containing pattern
dircount=1 # Count of directories searched
foundcount=0 # Count of files containing pattern
# Define a function
recursivegrep () {
for node in `ls`
do
if test -d $node
then
# If node is a directory, move into directory and call
# this function
dircount=`expr $dircount + 1`
cd $node
echo -n ". "
pwd >> $dirfile
recursivegrep
cd ..
else
# If file is an ascii file, grep for pattern and include
# filename and line number (tee output to standard out and
# append to file).
if test -f $node
then
if found=`grep -i -n -H $pattern $node`
then
foundcount=`expr $foundcount + 1`
echo -n "$node($foundcount) "
echo "DIRECTORY:`pwd`
$found" >> $outfile
echo "`pwd`/$node" >> $filelist
fi
fi
fi
done
}
# Create output files
>$outfile
>$filelist
echo "DIRECTORIES SEARCHED" > $dirfile
pwd >> $dirfile
eoldos [+]
echo "
Directories searched will be stored in $dirfile
Files containing $pattern will be stored in $outfile
Dots show directories being searched
filename(n) is a file containing $pattern and current (count) of files
"~
:~
# Start recursively grepin'
echo -n "Starting search at: `pwd` "
recursivegrep
echo -n "
Directories searched: $dircount
Files found containing "$pattern": $foundcount
Directories searched stored in: $dirfile
List of files containing "$pattern" stored in $filelist
Grep output stored in: $outfile
v - vim the list of files containing "$pattern"
f - vim the actual files containing "$pattern"
r - remove these temporary output files
q - quit
Enter option: "
read reply
case "$reply" in
v) vim $filelist ;;
f) vim `cat $filelist` ;;
r) rm $outfile $dirfile $filelist ;;
esac
Comments (0)
You don't have permission to comment on this page.