Monthly Archives: September 2011

nawk/grep script for counting occurences on line before

I was helping out a co-worker of mine construct a script to find/count occurrences of a given string that occur on a line preceding another given string. Using GNU grep, this would be easy:

grep -B 1 tofind FILE_PATTERN | grep -c tofindabove

Unfortunately, Solaris does not use GNU grep, so I had to resort to using nawk + grep:

nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=1 a=0 s="tofind" FILE_PATTERN | grep -c tofindabove

where within the nawk command,
b: number of lines before match to display
a: number of lines after match to display
s: string to match

Credit for the usage of the nawk command in this context.