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? – Stéphane Chazelas Feb 11 '20 at 12:05
  • nope, only have usr/bin/grep – Jman91 Feb 11 '20 at 12:51
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 – Jman91 Feb 11 '20 at 13:07
  • Excellently elegant! – G-Man Says 'Reinstate Monica' Feb 11 '20 at 22:21

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.