#!/bin/ksh
#< Display lines before and/or after a match in a file
# usage:
# lgrep "searchterm" lines_before lines_after inputfile
# e.g. lgrep "^something.*" 0 10 inputfile
if [ "$#" -ne "4" ]; then
echo "Usage: $(basename $0) \"searchterm\" lines_before lines_after inputfile" >&2
exit 1
fi
matchstring="$1"
lines_before="$2"
lines_after="$3"
matchfile="$4"
if [ ! -e "${matchfile}" ]; then
echo "Error: ${matchfile}: no such file" >&2
exit 1
fi
echo "${lines_before}" | egrep "^[0-9]+$" >/dev/null 2>&1
if [ "$?" -ne "0" ]; then
echo "Error: ${lines_before} not an integer" >&2
exit 1
fi
echo "${lines_after}" | egrep "^[0-9]+$" >/dev/null 2>&1
if [ "$?" -ne "0" ]; then
echo "Error: ${lines_after} not an integer" >&2
exit 1
fi
matches=`echo "${line}" | egrep -n "${matchstring}" ${matchfile}`
if [ "$?" -ne "0" ]; then
echo "No match" >&2
exit 1
fi
echo "${matches} " | while read line; do
lineno=`echo "${line}" | cut -d: -f1`
match=`echo "${line}" | cut -d: -f2`
# echo "Match found - line ${lineno} - ${match}"
minline=$(( lineno - ${lines_before} ))
[[ "$(( lineno - ${lines_before} ))" -lt 1 ]] && minline=1
[[ "${lines_before}" -gt "0" ]] && \
sed -n "$minline,$(( lineno - 1 ))p" ${matchfile}
sed -n "$lineno p" ${matchfile}
[[ "${lines_after}" -gt "0" ]] && \
sed -n "$(( lineno + 1 )),$(( lineno + ${lines_after} ))p" ${matchfile}
done
exit 0