perl -ne 'BEGIN{$_=shift for$B,$A,$p}/$p/and@l=(),do{<>for 1..$A},next;push@l,$_;print shift@l if$B<@l}{print@l' 3 5 pattern test.txt