SED – Print Lines Before and After Pattern Match Excluding Other Patterns

awkgrepsed

I use awk on Solaris to print 5 lines before and after a pattern match. Currently, the following one-liner does the job:

/usr/xpg4/bin/awk '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=5 a=5 s="ERROR" file

However, the result is not satisfactory. First of all, it contains unwanted lines like

  • lines with the match itself
  • empty lines
  • lines matching the (unwanted) patterns like
    • remove
    • nonsense
    • stupid

Additionally, there is a requirement that each founding should be separated by a line with some dashes.

Sample input:

stupid
remove

keep it
*
MATCH
keep it as well



remove

important
                                                     *
MATCH at line 2:
needed
also

this line should be kept
                                                     *
MATCH at line 2:
this to save
very important



remove

keep it
*
MATCH
keep it as well

nonsense
another nonsense

Expected output:

keep it
keep it as well
---
important
needed
also
---
this line should be kept
this to save
very important
---
keep it
keep it as well

How can achieve it in a possible elegant way?

Best Answer

Though the expected output is not clear, I will try. If you have the gnu utils on Solaris, you can use gawk and ggrep in a very simple manner:

gawk 'NF > 0' fileName  |ggrep -C5 pattern

You can add a | ggrep -v somePattern at the end to filter out unwanted words.