use strict; my $flag = 0; my $few = shift || 2; while () { print $_ if ($flag-- > 0); $flag = $few if (/Update certificate/); } __DATA__ Useless line before match Feb 19 15:22:21 206021 152221.684878 7219 INFO: Update certificate for user=(XXX) , updated by XXX First line after match Second line after match Third line after match Fourth line after match #### H:\perl> perl 1156056.pl First line after match Second line after match H:\perl>perl 1156056.pl 3 First line after match Second line after match Third line after match