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