my $file = 'fred.txt'; my $tmp = 'fred.txt.tmp' . $$; # habitually I make tmp files unique in case of multiuser usage. open my $ih, $file; open my $oh, ">$tmp"; while ( <$ih> ) { /My_Name/ and $_ = '## ' . $_ . "\n" ; # although a carriage return is already present print $oh $_; } close $ih; close $oh; rename ( $tmp, $file );