How to replace a string in an existing file in Perl?

None 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);

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 extension
  • The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line

Tags:

Regex

Perl