foreach my $contract (@contracts) { open (Contract1, "<", $contract) || die("Cannot open input file $contract: $!"); my @all; while () { if (/Management Fees/i) { # Print this line push @all, $_; # And the next 19 lines too for (my $i=0; $i<($linescount-1); $i++) { my $line = ; last if !defined $line; push @all, $line; } } } close Contract1; # Base output filename on original filename. my $outfile = "$contract".".output"; open (Contract1a, ">", $outfile) || die("Cannot open output file $outfile: $!"); print Contract1a join("\n",(@all)); close Contract1a; }