Linux Recursive Grep
update I've reformatted the perl script to make its functionality clearer. I've also removed a typo(!) from the call to egrep, added semicolons and placed another comment in the help output.
Fun with Linux, part 2:
A script I call "regrep" for recursive egrep:
#!/bin/sh
if [ "$1" = "--help" ]; then
echo "Usage: regrep <string> <directory>";
echo "Recursively searches all files in <directory> for <string>";
echo "This is basically a wrapper for: egrep -rn <string> <directory>";
else # run the command
if [ "$2" = "" ]; then
directory=(".");
else
directory=$2;
fi
pushd $directory > /dev/null;
egrep -rn "$1" * | colorGrepOutput.pl;
popd > /dev/null;
fi
and the perl script, "colorGrepOutput.pl" it refers to is:
#!/usr/bin/perl
while (<>) {
if ($_ =~ /^BINARY.*/) {
; # do nothing
} elsif ($_ =~ /^([^:]*)(:)([^:]*)(:)(.*)/) {
print "\033[1;34m"; # start blue
print $1; # file name
print "\033[0m"; # end blue
print $2; # first colon
print "\033[1;36m"; # start aqua
print $3; # line number
print "\033[0m"; # end aqua
print $4; # second colon
print $5; # matching text
print "\n";
}
}
Example usage:
$ regrep "old_contact@whatever.com"
The scrip does not work correctly as written, the error message is mentioning line 12:
directory=(".");
I've been using it for over a year now, without errors.
What shell are you using and what, precisely, is the error message?
Posted by: Joe Grossberg on October 9, 2003 6:10 PM | permalink#hi everyone,
#below there is simple shell script for
#traversing on an entire directory tree.
#having added your shell command
#in the commented parts(see below)
#you will have any command's recursive version
#
GLB_VAR=0;
function recursive
{
cd "$1" 2> /dev/null
GLB_VAR=$?
if [ $GLB_VAR -eq 0 ]
then
echo Current Directory is `pwd`
#add your command here,
# if it is used for whole directory
# $i holds the directory name
for i in *
do
if [ "$i" = "*" -o -h "$i" -o -c "$i" ]
then
continue
fi
if [ -d "$i" -a -r "$i" ]
then
recursive "$i"
if [ $GLB_VAR -eq 0 ]
then
cd ..
else
GLB_VAR=0;
fi
else
#add your command here,
#if your command is used on files one-by-one
#$i holds name of file
continue
fi
done
fi
}
if [ -z $1 ]
then
recursive .
else
if [ -d $1 -a -r $1 ]
then
recursive $1
else
echo $1 : No Such a Directory!
exit
fi
fi
Posted by: alyosa karamazof on December 17, 2003 7:49 AM | permalinkThanks Alyosa.
I appreciate your script's flexibility. Sorry that my comments don't preserve whitespace. :(
Posted by: Joe Grossberg on December 17, 2003 2:38 PM | permalinkNo more comments! Either someone has violated Godwin's Law, I'm tired of the discussion or, most likely, the ten-week window has closed. You can, however, contact me through email.