in reply to Re^2: find & replace a string in perl
in thread find & replace a string in perl
There is no need for a substitute regex here. Nor is there a need for a "/g" global match. Just add a # at the front if the line contains at least one boundary separated token of "test".
Update:I modified the code with another thought...when writing filters like this, it is usually a good idea to have the property that running the filter more than once is "harmless". In this case, I prevent multiple # from showing up at the front of the line by just a little addition to the "if" clause.
#!/usr/bin/perl -w use strict; my $file_name = "test.txt"; open(my $in, '<', $file_name) || die "cannot open $file_name for read + $!"; open(my $out, '>', "$file_name.tmp") || die "cannot open $file_name.tm +p for write $!"; while( <$in>) { print $out "#" if(/\btest\b/i && !/^#/); #only one # at front of li +ne print $out $_; } close ($in); close ($out); # save copy of original file rename ($file_name,"$file_name.bak") || die "problem with rename $!"; # replace original with the modified version rename ("$file_name.tmp", $file_name) || die "problem with rename $!"; = file test.txt before running program testing is requrired see/for/test test/data/istesting = file test.txt after running program testing is requrired #see/for/test #test/data/istesting
|
|---|