A customer wanted to search a bunch of files and find all the files that contained particular keywords, but the standard grep output controls were inappropriate for the use case:  grep -H prints the filename at the beginning of each and every line, whereas grep -h omits the filename from each and every line.  Thus, the desired behavior was:

filename1
hit1
hit2
hit3

filename2
hit1
hit2
hit3

It took a bit of research and tinkering to get a script working properly, so it is provided here for future reference.

https://github.com/fredzannarbor/pagekicker-community/blob/master/scripts/bin/grepclips

#!/bin/bash
# recursively greps directory
# for each file that contains caseinsensitive matches
# provides filename followed by matches

# sets defaults 

afterKWIC=0
beforeKWIC=0
path="."

while :
do
case $1 in
--help | -\?)
usage:
grepclips -p "search phrase" -P /path/to/dir -A "context lines after" -B "context lines before"
exit 0 # This is not an error, the user requested help, so do not exit status 1.
;;
-p|--pattern)
pattern=$2
shift 2
;;
-p|--pattern=*)
pattern=${1#*=}
shift
;;
-P|--path)
path=$2
shift 2
;;
-P|--path=*)
pattern=${1#*=}
shift
;;
-A|--afterKWIC)
afterKWIC=$2
shift 2
;;
-A|--afterKWIC=*)
afterKWIC=${1#*=}
shift
;;
-B|--beforeKWIC)
beforeKWIC=$2
shift 2
;;
-B|--beforeKWIC=*)
beforeKWIC=${1#*=}
shift
;;
 --) # End of all options
 shift
 break
 ;;
 -*)
 echo "WARN: Unknown option (ignored): $1" >&2
 shift
 ;;
 *) # no more options. Stop while loop
 break
 ;;

esac
done

if [ ! "$pattern" ]; then
 echo "ERROR: option '-p [pattern]' not given. See --help" >&2
 exit 1
fi


grep -r -l -i "$pattern" "$path" | while read fn
do
 echo "$fn:"
 grep -i "$pattern" --no-group-separator -h -A "$afterKWIC" -B "$beforeKWIC" "$fn"
 echo " "
done            break
            ;;
        -*)
            echo "WARN: Unknown option (ignored): $1" >&2
            shift
            ;;
        *)  # no more options. Stop while loop
            break
            ;;

esac
done

grep -r -l -i "$pattern" "$path" | while read fn
do
  echo "$fn:"
  grep -i "$pattern" --no-group-separator -h -A "$afterKWIC" -B "$beforeKWIC"  "$fn"
  echo " "
done
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s