#!/usr/bin/perl $howmany=3; # 3 lines before match, 3 lines after match $match="match"; # What to search i.e. grep string @buff=(); # Array that contains (($howmany*2)+1) elements max at any given time $cLines=(($howmany*2)+1); #Read first (($howmany*2)+1) lines into @buff $count=0; while(defined($line=) && $count<$cLines) { chomp($line); push(@buff,$line); $count++; } #start from @buff[0], go until index ($howmany) for($idx=0;$idx<=$howmany and $idx )) { chomp($line); shift @buff; push(@buff,$line); if($buff[$howmany]=~/$match/) #Always match element at index $howmany { print "\n"."*" x 20; #Separator #Print $howmany lines before match for($idx=0;$idx<$howmany;$idx++) { print "\n$buff[$idx]"; } print "\n$buff[$idx] <----- match"; #Print line that matches #Print $howmany lines after match for($idx+=1;$idx0?$left:0;$jdx<$idx and $jdx