in reply to Re: How to print 5 lines below after a regex match
in thread How to print 5 lines below after a regex match

Thanks I see the lines posted below my match. One last thing which I should have included, how do also print the matched line as well. Many thanks

  • Comment on Re^2: How to print 5 lines below after a regex match

Replies are listed 'Best First'.
Re^3: How to print 5 lines below after a regex match
by poj (Abbot) on Feb 24, 2016 at 20:43 UTC

    Set the flag first then print

    use strict; my $flag = 0; my $few = shift || 3; while (<DATA>) { $flag = $few if (/Update certificate/); print $_ if ($flag-- > 0); }
    poj
      It really depends on what the OP really needs, but there is a danger of $flag being reset while it is reading the next "few" lines, if the regex matches again. Perhaps something like this:
      use strict; my $few = shift || 3; while (<DATA>) { if (/Update certificate/) { print $_; print scalar <DATA> for 1..$few; } }
      Or possibly for 1..$few-1;, depending on whether $few includes the matching line or not.