jgrep (Source)

#!/bin/bash
##---------------------------------------------------------------------------##
#
#   Program:    jgrep
#   Author:     Brian <genius@groupbcl.ca> :)
#   Date:       December 2012
#
#   Run 'egrep -rn' (or -irn) and create a nicely formatted set of results
#   Alternatively, reformat the output from a pipeline of one or more 
#   '(e)grep' or '(e)grep -n' commands.
#
##---------------------------------------------------------------------------##
# BUUS: This script is part of Brian's Useful Utilities Set

if [ "$1" = '-h' -o "$1" = '--help' ]
then
    echo
    echo "usage: jgrep [-i] 'regexp' [file ...]"
    echo "  If file is not specified, defaults to '*' and recurses subdirectories"
    echo
    echo "If filename is '-', jgrep operates on stdin:"
    echo "  grep -Hn regexp file [file ...] | jgrep regexp -"
    echo
    echo "If no parameters, jgrep assumes it's processing output from a pipeline:"
    echo "  grep -Hn regexp file [file ...] | grep regexp | jgrep'"
    echo
    exit 1
fi

#--- Did the user pass '-i' in the first param?
EGREP_SWITCHES='-Hn -ar'
#               ^^^^ dropped if $1 is '-'
if [ "$1" = '-i' ]
then
    EGREP_SWITCHES="${EGREP_SWITCHES} -i"
    shift
fi

#--- Get the regular expression
EGREP_EXPR="$1"
shift

#--- Did user supply a filename?
if [ "$1" ]
then
    ALL_FILES=''
else
    ALL_FILES='*'
fi

# An input filename of '-' needs special handling: remove the '-H' switch to
# prevent '(standard output):' from appearing in the output, and remove -n
# because it's assumed to be part of the initial (e)grep
[ "$1" = '-' ] && EGREP_SWITCHES="${EGREP_SWITCHES:4}" 

#--- Perform the search (if necessary) and format the results
AWK_PROGRAM='
    BEGIN { prev_fn = "__FIRST_FN__" }

    $1 != prev_fn {
        if (prev_fn != "__FIRST_FN__") { print "" }
        print $1 ":"
        prev_fn = $1
    }

    { printf("%6i: %s\n"), $2,  substr($0, length($1)+length($2)+3) }
'

if [ "$EGREP_EXPR" ]
then
    egrep $EGREP_SWITCHES "$EGREP_EXPR" "$@" $ALL_FILES | awk -F: "$AWK_PROGRAM"
else
    cat - | awk -F: "$AWK_PROGRAM"
fi

# vim: tabstop=4