How to grab multiple lines after matching a line in Perl? -


my file looks this:

1  15 2  16 3  18 4  19 5  25 6  30 7  55 8  45 9  34 10 52 

if matched pattern 30 in line 6, grab n lines before , m lines after line 6, example if n=3 , m=4 result expected this:

3  18 4  19 5  25 6  30 7  55 8  45 9  34 10 52 

i new beginner in perl , advice appreciated.

﹟update many these helpful advice below , appreciate them. here updated code , suggestions welcome!

my $num;  while(<>) {    if ( /pattern/)  {$num = $. ;}    }  open (,"") || die ("can't open file");  while(<>)  { if (  $. >= $num-n , $. <=$num+m) {     print out "$_ \r"; } } 

maintain array (i'll call @preceding) of last n lines read. when pattern matched, stop updating array , start inserting lines array (@following). until @following has m lines in it.

it should (fixed ikegami):

my $matched = 0; @preceding; @following; while(<>){     if ($matched){         push ( @following, $_);         last if @following == m;         next;     }     else {         push ( @preceding, $_);         shift(@preceding) if @preceding > n;     }     $matched = 1 if /pattern/; } 

Comments