use strict; my @files = glob "file*.txt"; my $file; foreach $file(@files){ if($file =~ /^file(\d{4})\.txt$/){ my $num = $1; $num =~ s/^0*//; open(IN, $file)||die "cannot open $file for read:$!\n"; open(OUT, ">tmp.txt")||die "cannot open tmp.txt for write:$!\n"; while(){ s/stuff into/stuff where thing="$num" into/i; print OUT; } close IN||die "cannot close $file:$!\n"; close OUT||die "cannot close tmp.txt:$!\n"; rename('tmp.txt', $file); } }