foreach $list (@list) { if ($list =~ m/\/if\/home\/m1hrb00\/covenants\/Contracts\/(.*)\.txt/) { #select the index of contract names, trim off the filepath push (@contract_list, $1); print STDERR "$1 \n"; } } $beforecount = 10; #set how many lines before the match you'd like to pull; $aftercount = 10; #set how many lines after the match you'd like to pull; foreach (@contract_list) { #pull in the array of contracts open Contract1, "<./$_.txt \n"; @lines = ; close Contract1; my $contents = join "", @lines; @all = undef; shift @all; #loop for Governance $infile = "$_"; my $incontract = "$infile".".txt"; print STDERR "$incontract read \n"; while ($contents =~ m/Governance/i) { if ($contents =~ m/((\n.*){$beforecount}Governance(.*\n){$aftercount})/i) { push (@all, "$1\n"); print STDERR "$1\n"; $contents =~ s/Governance//i; $contract = "$_"; my $outfile = "$contract".".txt"; open (Contract1a, ">", "/if/home/m1hrb00/covenants/CorporateGovernance/Governance/$outfile") || die("Cannot open output file $outfile: $!"); print Contract1a join("\n", (@all)); print STDERR "$outfile matched \n"; close Contract1a;