I want to replace the word "blue" with "red" in all text files named as 1_classification.dat, 2_classification.dat and so on. I want to edit the same file so I tried the following code, but it does not work. Where am I going wrong?
@files = glob("*_classification.dat"); foreach my $file (@files) { open(IN,$file) or die $!; <IN>; while(<IN>) { $_ = '~s/blue/red/g'; print IN $file; } close(IN) }
Performing a regex search-and-replace is just as easy: $string =~ s/regex/replacement/g; I added a “g” after the last forward slash. The “g” stands for “global”, which tells Perl to replace all matches, and not just the first one.
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.
Use a one-liner:
$ perl -pi.bak -e 's/blue/red/g' *_classification.dat
Explanation
-p
processes, then prints <>
line by line-i
activates in-place editing. Files are backed up using the .bak
extensionNone of the existing answers here have provided a complete example of how to do this from within a script (not a one-liner). Here is what I did:
rename($file, $file . '.bak'); open(IN, '<' . $file . '.bak') or die $!; open(OUT, '>' . $file) or die $!; while(<IN>) { $_ =~ s/blue/red/g; print OUT $_; } close(IN); close(OUT);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With