in reply to Search String - next line

The solution is quite simple if you only expect to see the target pattern in the file once. Then you just look for the pattern, count n more lines, print the last of those, and bail.

But if the pattern can appear more than once, it gets tricky, since it may be that n = 5 (say) but the pattern is seen a second time only 3 lines after the first. Then you sort of need to remember which line numbers will need to be printed out, and print them as you come to them.

Here's my solution (tested):

my $pattern = qr/match this string!/; my $n = 4; my @li; while(<>) { if ( @li && $. == $li[0] ) { print; shift @li; } /$pattern/ and push @li, $. + $n; }
Of course, a clever perl programmer can condense this to a one-liner, but I figure it's better to show clearly what's really going on.