2

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?

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

1 Answer 1

1

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .