I am trying to add recursive support to my filegrep script.
For some reason this does not work as expected:
RECURSIVE_MODE=off
# iterate over args
for ARG in "$@"
do
if [ -d "$ARG" ] && [ $RECURSIVE_MODE = on ] ; then
# recursive call
$0 $GREP_ARGS $ARG/*
elif [ -f "$ARG" ]; then
filecat "$ARG" | grep $GREP_ARGS | sed "s#^#$ARG: #"
else
[ "$ARG" = "-r" ] && RECURSIVE_MODE=on
# append to the current grep args
GREP_ARGS="$GREP_ARGS $ARG"
fi
done
I'd like to avoid using functions in this case for better readability.
EDIT: the script should work like this:
for each passed arg:
- if the current arg is a directory, check if recursive mode is enabled and if yes do the recursive call;
- else if the current arg is a file, call
grep
with the current pattern; - else assume the current arg is a grep pattern or a grep switch and append it to the current
$GREP_ARGS
list.
Maybe this is not completely reliable, but it works fine for me as a replacement for zgrep
, pdfgrep
, etc.
|
in extended regexps or\|
in basic RE), as well as the available command-line options ofgrep
(e.g.-r
for recursing a directory). For example: e.g.grep -E -r 'pattern1|pattern2|pattern3|...|patternN' /path/to/directory/
. Also worth noting is thatgrep
already knows how to deal with multiple file or dir arguments. Your wrapper script is entirely superfluous - it doesn't do anything thatgrep
doesn't already do. Readman grep
.grep
cannot parse binary files natively (that's why there are wrappers likezgrep
,pdfgrep
, etc.).# append to the query pattern
comment mean, then?zgrep
may not understandgrep
's-r
option, but that's whatfind ... -exec
is for. BTW,pdfgrep
isn't a wrapper aroundgrep,
it's a stand-alone program. My point, however, was that by not bothering to learn to use existing tools, you are making things much more difficult for yourself than they need to be and, worse, re-inventing those tools poorly.$PATTERN
toGREP_ARGS
to avoid confusion.