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.

Advertisements
This entry was posted in Scripting, Solaris and tagged , , , , , . Bookmark the permalink.

2 Responses to nawk/grep script for counting occurences on line before

  1. Nadeem Rashid says:

    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

  2. Nadeem Rashid says:

    grep -i ‘Exception’ Filename | tr -s ‘[ ]’ ‘[ ]’ | tr ‘[ ]’ ‘[\n ]’ | grep -i ‘xception’ | tr -s ‘[\t]’ ‘[\n ]’ | tr -s ‘[[]’ ‘[\n]’ | tr -s ‘[]]’ ‘[\n]’ | tr -s ‘[-]’ ‘[\n]’ | tr -s ‘[>]’ ‘[\n]’ | tr -s ‘[:]’ ‘[\n]’ | tr -s ‘[<]' '[\n]' | tr -s '[ ]' '[\n ]' | grep -i 'xception' | sort | uniq -c | sort -n

    try this also for print a pattern matching and count

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s