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

Jman91
  • 45

1 Answers1

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).