recursive grep

13mb80000-HallM(10053584)37x10 marcus@bighorn.dr.lucent.com
Thu Sep 30 23:42:00 GMT 1999


> 
> Here is a simple rgrep I use, never tried it with bash
> however.
> 
> #!/bin/ksh
> for FILE in `find . -name $2 -print`
> do
> 	if [ `grep -c $1 $FILE` -ne 0 ]
> 	then
> 		echo $FILE
> 		grep -i -n $1 $FILE
> 	fi
> done
> 
> Carson

A much more efficient script here would be:

#!/bin/ksh
pat=$1
shift
find "$@" ! -type d | xargs grep -n -i $pat /dev/null

(Of course, the -n and -i could be left out if that is your preference,
and there could be some attempt to parse them from the script's arguments
instead of building them into the script).

Problems with the original script (for illustration purposes, not meant to
criticise):

	1: The setup for the for loop builds the entire iteration list
	from the output of the find.  If this is really big, some systems
	start to have a problem (because it all has to be in an argument
	vector)
	
	2: The first grep doesn't have the -i, so it requires explicit
	case matching, unlike the 2nd grep (likely a minor oversight).
	
	3: The script starts up one (or two!) grep processes for each and
	every file searched.  This can be costly if there are many files.

One subtle thing about my solution is that the /dev/null argument is passed
to grep.  This is because if grep has only one file argument, it will not
prefix the matched line with the file name.  Giving grep the /dev/null before
whatever arguments xargs tacks on ensures that grep will always have two
file arguments and therefore will always print the file name.

marcus hall

--
Want to unsubscribe from this list?
Send a message to cygwin-unsubscribe@sourceware.cygnus.com



More information about the Cygwin mailing list