0

I have a text file say input.txt which contains below data

$ cat input.txt text1 error text2 text3 text4 xyz asd asdf text10 error text11 text12 text13 text14 def ghi jkl text16 error text17 text18 text19 text20 

I'm searching for 'error' in input file. So I need to print the previous one line and next 4 lines when pattern matches. Also, the patter can occur in multiple times.

I need output as below

text1 error text2 text3 text4 text10 error text11 text12 text13 text14 text16 error text17 text18 text19 text20 

Operating system is Solaris, So grep -A doesn't work here

2
  • Don't you have GNU grep at /usr/gnu/bin/grep? Commented Feb 11, 2020 at 12:05
  • nope, only have usr/bin/grep Commented Feb 11, 2020 at 12:51

1 Answer 1

4

With awk:

awk '/error/ {n = 6} n {print prev; n--} {prev = $0} END {if (n) print} ' < your-file 

Or to add an empty line between those groups of 6 (assuming no overlapping) lines:

awk '/error/ {n = 6; if (x++) print ""} n {print prev; n--} {prev = $0} END {if (n) print} ' < your-file 

Make sure to use /usr/xpg4/bin/awk, nawk or /usr/gnu/bin/awk on Solaris. The one in /bin is ancient from the 70s and doesn't support the modern standard syntax.

If you have /usr/gnu/bin/awk though (text/gawk package), chances are you have /usr/gnu/bin/grep as well (text/gnu-grep package) and could then use its -A/-B extensions:

/usr/gnu/bin/grep -B1 -A4 error < your-file 

(GNU grep separates non-overlapping groups with -- lines).

2
  • it works like charm :D, can you also help me in adding an extra new line "\n" after each iteration, like after each match and prints all the 6 lines extra new line needs to be added Commented Feb 11, 2020 at 13:07
  • Excellently elegant! Commented Feb 11, 2020 at 22:21

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.