3

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?

  • Show input and expected output. – 123 Feb 10 '16 at 14:24
  • Sample input / expected output added. – nickm Feb 10 '16 at 18:26
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.