#!/bin/bash
## Author: Alex Efros <powerman-asdf@yandex.ru>, 2008
## License: Public Domain
##
## rgrep: Replacement for `grep -r` using `find | xargs zgrep -P`.
##
## First 0 or more optional params starting with "-" plus one required
## param don't starting with "-" rgrep gives to "zgrep -P"; all other
## params rgrep gives to "find -type f". Example:
##   $ rgrep -i 'perl-compatible regexp here' /path/to/ -maxdepth 2 -name 'a*'
##
## This script is especially useful for searching directories which contain
## special files like pipes - because usual grep hang on these files.

VERSION="2.00"

trap "kill -9 -$$" 2	# zgrep refuse to die on Ctrl-C

declare -a p
for n in $([ $# -ne 0 ] && seq $# || false)
do
    i=$(($n-1))
    p[$i]=$1
    shift
    [ "${p[$i]:0:1}" != "-" ] && break
done
if [ ${#p[@]} -gt 0 ] && [ "${p[ $((${#p[@]}-1)) ]:0:1}" != "-" ]; then
    find "$@" -type f -print0 | xargs -0 zgrep -P "${p[@]}"
else
    echo "No search pattern: find $@ | grep ${p[@]}"
    echo
    grep '^##' "$0" | sed s,...\\?,,
fi

