Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, A lot of of the available methods show how to find a range of lines between line numbers or between pattern match. But is it possible to find a pattern match then print the 5 lines after the pattern match, without any knowledge of the line number etc? Thanks

Replies are listed 'Best First'.
Re: range of lines
by Fletch (Bishop) on Jun 21, 2004 at 13:19 UTC
    while( <IN> ) { if( /zagnork/ ) { print scalar <IN> for 1..5; } }
Re: range of lines
by kesterkester (Hermit) on Jun 21, 2004 at 13:23 UTC
    This probably isn't the most clever way, but it'll do the job: set a counter to the number of lines you want to print out after data matches the pattern, and then 1) print out the line if the counter is positive, and 2) decrement the counter for each line that's printed out.

    use warnings; use strict; my $nLines = 0; while (<DATA>) { $nLines = 5 if /kjkjkjkj/; print if $nLines-- > 0; } __DATA__ 1asdfasdf 2asdfasdf 3kjkjkjkjkj 4asdfasdf 5asdfasdf 6asdfasdf 7asdfasdf 8asdfasdf 9asdfasdf 10asdfasdf

    Outputs:

    3kjkjkjkjkj
    4asdfasdf
    5asdfasdf
    6asdfasdf
    7asdfasdf
    
Re: range of lines
by artist (Parson) on Jun 21, 2004 at 15:39 UTC
    On Unix, you may be able to accomplish with this.
    grep -A5 pattern file
Re: range of lines
by delirium (Chaplain) on Jun 21, 2004 at 15:20 UTC
    If you happen to want the matching line printed in addition to the 5 lines after it, you could use the .. operator like so:

    perl -ne 'print if /PATTERN/ .. ++$c%6==0;' file.txt

      Ahhh, that's a very clever way to do it. ++delirium!