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

i need help with the following input : abcd diff random data(any number of lines) efgh diff random data(any number of lines) What I exactly need to do is when regex finds diff,I need to start printing from the next N line till it reaches the next diff.So basically I am trying to open a file from the position where regex is matched and then somehow get to print whatever is in the next lines. Could you please help me do this.
  • Comment on Print next N lines after a pattern is matched.

Replies are listed 'Best First'.
Re: Print next N lines after a pattern is matched.
by roboticus (Chancellor) on Jul 22, 2011 at 19:13 UTC

    manutd:

    What exactly are you having trouble with? Just read the file line by line, and when you find the regex, set a counter to N, and then for each line thereafter, print the line if the variable is greater than zero. Then decrement the variable and continue the loop.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Print next N lines after a pattern is matched.
by ikegami (Patriarch) on Jul 22, 2011 at 19:33 UTC
    my $print = 0; while (<>) { if (/diff/) { $print = $N; } elsif ($print) { --$print; print; } }
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Print next N lines after a pattern is matched.
by JavaFan (Canon) on Jul 23, 2011 at 16:56 UTC
    Your question is unclear. What if the next diff is after N+2 lines? I think your question is one of:
    • Print the next N lines after a match.
    • Print all lines between two matches.
    But it's unclear to me which of the two you want.