in reply to printing several lines around match
#!/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 g +iven time $cLines=(($howmany*2)+1); #Read first (($howmany*2)+1) lines into @buff $count=0; while(defined($line=<DATA>) && $count<$cLines) { chomp($line); push(@buff,$line); $count++; } #start from @buff[0], go until index ($howmany) for($idx=0;$idx<=$howmany and $idx <scalar @buff;$idx++) { if($buff[$idx]=~/$match/) { print "\n". "-" x 20;#Separator #Print $howmany lines before match for($jdx=0;$jdx<$idx and $jdx<scalar(@buff);$jdx++) { print "\n$buff[$jdx]"; } print "\n $buff[$jdx] <---- match"; # print line that matches #Print $howmany lines after match for($jdx=$idx+1;$jdx<($idx+$howmany+1) and $jdx< scalar(@buff +);$jdx++) { print "\n$buff[$jdx]"; } print "\n". "-" x 20;#Separator } else { print "\n$buff[$idx] <--- does not match"; } } #Start 'shifting' one element out of the array until end of file while(defined($line=<DATA>)) { chomp($line); shift @buff; push(@buff,$line); if($buff[$howmany]=~/$match/) #Always match element at index $howma +ny { 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;$idx<scalar(@buff);$idx++) { print "\n$buff[$idx]"; } print "\n"."*" x 20; #Separator } else { print "\n$buff[$howmany] <--- does not match"; } } print "\n". "=" x 20 . scalar(@buff). " elements";#Separator #At end of file, there are <=(($howmany*2)+1) elements left in @buff #BUt we have already seen $howmany elements in the while loop #So start matching from $howmany+1 for($idx=$howmany+1;$idx<scalar @buff;$idx++) { if($buff[$idx]=~/$match/) { print "\n". "-" x 20;; #Print $howmany lines before match $left=($idx-$howmany); for($jdx=($left)>0?$left:0;$jdx<$idx and $jdx<scalar(@buff);$ +jdx++) { print "\n$buff[$jdx]"; } print "\n $buff[$idx] <---- match"; # print line that matches #Print $howmany lines after match for($jdx=$idx+1;$jdx<($idx+$howmany+1) and $jdx< scalar(@buff +);$jdx++) { print "\n$buff[$jdx]"; } print "\n". "-" x 20;; } else { print "\n$buff[$idx] <--- does not match"; #shift @buff; } } __DATA__ first line contains match second does not third does not either this third line contains one match fourth one again matches fifth sixth seventh eighth ninth tenth eleventh enough! now match something match this too more match ok not any more ENOUGH!!!! no no no no nanananananana hohhohohohohohp lol duck tecm who are you and what nonsense is this hahaha match here!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: printing several lines around match
by auto_w (Novice) on Jun 20, 2012 at 08:31 UTC |