Yogsototh

Multi-line grep

Posted in script by yogsototh on May 4, 2009

After many, many times I use many different tricks to implement a multi-line grep, I’ve done one myself I called it <code>mlegrep</code>:

#!/usr/bin/env zsh

separator='\n\n'
while [[ ${1[1]} = '-' ]]; do
    case ${1[2]} in
        F) separator="${1[3,-1]}" ; shift ;;
        *) print "unknown option : $1" >&2; exit 2 ;;
    esac
done

if (($#>1)); then
    print   "usage: $0:t [-Fseparator] REGEXP [FILE ...]" >&2
    exit 1
fi

value="$1"
shift
perl -ne 'BEGIN{$/="'$separator'";} if ( $_ =~ m/'$value'/ ) { print }' "$@"

hope this help,
Y.

Leave a Reply