Print lines before and after pattern match

I am using Solaris, I want to print

  • 3 lines before pattern match
  • pattern
  • 5 lines after pattern match

Pattern is abcd to be searched in a.txt. Looking for the solution in sed/awk/perl. Thanks ..

Input File a.txt:

1
2
3
abcd
4
5
6
7
8
1
2
3
xyz
4
5
6
7
8
1
2
3
abcd
4
5
6
7
8
 

Desired Output:

1
2
3
abcd
4
5
6
7
8
1
2
3
abcd
4
5
6
7
8

Thanks,

check whether your grep supports -A and -B option

Or with awk:

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=3 a=5 s="abcd" file

Use nawk or /usr/xpg4/bin/awk on Solaris.

1 Like

Franklin, You are correct. :b:

Can we figure out anything in sed.

Try this:

sed '/abcd/i \1\n2\n3' <inputfile> | sed '/abcd/a \4\n5\n6\n7\n8'

Try this

grep -B 3 -A 5 abcd a.txt

It is not working on Grep available to me :wink:

-A, -B, -C will be available in gnu grep

http://www.gnu.org/software/grep/manual/grep.txt

`-A NUM'
`--after-context=NUM'
     Print NUM lines of trailing context after matching lines.

`-B NUM'
`--before-context=NUM'
     Print NUM lines of leading context before matching lines.

`-C NUM'
`-NUM'
`--context=NUM'
     Print NUM lines of leading and trailing output context.