Perl script to extract 2 lines before and after the pattern matching

perl

my file is like

line 1 
line 2 
line 3
target
line 5
line 6
line 7

I can write a regex that matches the target. What all I need is I need to grab lines 2,3,5,6.
Is there any way to do it?

Best Answer

If you're not determined to use perl you can easily extract the context you want with grep and Context Line Control options

grep -A 2 -B 2 target filename | grep -v target

Of course target will need to be replaced by a suitable regex.

Related Topic