{C++ etc.}

Latest Posts
 
Home | C++ Posts | Linux Posts | Programming Posts | Issue Tracking Posts

Thursday, April 23, 2009

awk Search script with prior and following line capability

#!/bin/sh
# *********************************************************
# This uses nawk to list lines coming prior to and after
# the given search string.
# Format: xgrep
# ********************************************************
if [ $# != 4 ]
then
echo "Usage: $0 "
exit
fi
STR=$1
BEF=$2
AFT=$3
while [ ! -z "$4" ] ; do
echo ========== $4
nawk 'c-->0{print NR ":\t" $0;};$0~s{if(b)for(c=b+1;c>1;c--) print (NR-c + 1) ":\t" r[(NR-c+1)%b];print NR ":\t" $0;c=a}b{r[NR%b]=$0;}' b=$BEF a=$AFT s=$STR $4 | sed "s/^/$4\
/"
shift
done
echo ==========

Took me a while to understand how awk worked and customized the command I found on the net for my own needs.

No comments: