#!/usr/bin/perl use Getopt::Std; my %o; getopt 'b:a:',\%o; my $pat = shift; my @last; OUTER: while(<>) { if (/$pat/) { @last = (); for my $i(1..$o{a}) { $_ = <>; redo OUTER if /$pat/; } next; } push @last, $_; print shift @last if $o{b} < @last; } print @last;