PyrexKidd has asked for the wisdom of the Perl Monks concerning the following question:
I need to search a file for one of three patterns and replace it with one of three patters.
currently my code snippet looks like this:
while(<INFILE>){ $_ =~ s/$searchPattern1/$repalcePattern1/g; $_ =~ s/$searchPattern2/$replacePattern2/g; $_ =~ s/$searchPattern3/$replacePattern3/g; print OUTFILE $_; } # end while
Is there perhaps a more elegant way to do this? Also I would Like to print to screen conditionally based on the pattern replaced ie:
if ($_ == s/$searchPattern1/){ print("$searchPattern1 replaced with $replacePattern1 \n"); }elsif ($_ == s/$searchPattern2/){ print("$searchPattern2 replaced with $replacePattern2 \n"); }elsif ($_ == s/$searchPattern3/){ print("$searchPattern3 replaced with $replacePattern3 \n"); }else{ print("Search Patterns not found"); }
although at that point I can maybe change it to:
but that doesn't seem to be working... also as an aside is there a way to remove all the spaces at the end of a line and add a new line character? ie:while(<INFILE>){ if ($_ == s/$searchPattern1/){ $_ =~ s/$searchPattern1/$repalcePattern1/g; print("$searchPattern1 replaced with $replacePattern1\n"); }elsif ($_ == s/$searchPattern2/){ $_ =~ s/$searchPattern1/$repalcePattern1/g; print("$searchPattern2 replaced with $replacePattern2\n"); }elsif ($_ == s/$searchPattern3/){ $_ =~ s/$searchPattern1/$repalcePattern1/g; print("$searchPattern3 replaced with $replacePattern3\n"); }else{ print("Search Patterns not found"); } print OUTFILE $_; } # end while
<SOURCEFILE> foo bar <\n> foobar <\n> BlahBlah Blah <\n> to: foo bar<\n> foobar<\n> BlahBlah Blah<\n>
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Conditional Search and Replace
by ikegami (Patriarch) on May 01, 2010 at 00:16 UTC | |
Re: Conditional Search and Replace
by FalseVinylShrub (Chaplain) on May 01, 2010 at 08:03 UTC | |
Re: Conditional Search and Replace
by Hue-Bond (Priest) on May 01, 2010 at 08:53 UTC |