amarceluk has asked for the wisdom of the Perl Monks concerning the following question:

I am very new to programming, and I suspect the answer to this will be laughably obvious, but here goes: I want to use regular expressions to find and replace all occurrences of a string in an entire file. In the Q&A section I found a snippet to find a string in a file:
{ open(FILE, "sample.txt") or die "Can't open sample.txt\n"; local $/ = undef; $lines = <FILE>; close(FILE); } if($lines =~ /foo/) { print "A match was found\n" }
All very well and good. But how do I replace "foo" with "bar"? I tried this:
$lines =~ s/foo/bar/gms;
but it doesn't do anything to the other file. Help! Thank you!

Replies are listed 'Best First'.
Re: Regex to find/replace in a file
by VSarkiss (Monsignor) on May 16, 2002 at 19:08 UTC

    You're on the right track. After this: $lines =~ s/foo/bar/gms;the substitution has been made, but it's still in memory. The next step is to write it to the file:

    open(FILE, ">theother.txt") or die "Can't open the other file: $!\n"; print FILE $lines; close FILE;
    You said "other file", so I'm not sure if you want to overwrite the original file or not. If you do, just substitute its name instead of theother.txt above.

    HTH

      Thank you! It worked, and I'm extremely happy about it :-)
Re: Regex to find/replace in a file
by yodabjorn (Monk) on May 16, 2002 at 21:01 UTC
    This can also be done on the cmd line verry easily:
    perl -i.bak -lpe 's/foo/bar/g;' baz
    This would replace all occurances of foo with bar in file baz backing up the original (unalterd file) to baz.bak