in reply to substitute a word in the whole file .. how ???

As an addendum to dbwiz's solution: you may want to add word boundaries to the regexp if you want to avoid 'misfrogged' to be replaced by 'mistoadged' (ok, the example is contrived, but the potential problem isn't).

So the above would become:

perl -i.bak -pe 's/\bfrog\b/toad/g' txtfile

Hope this helps, -gjb-

Replies are listed 'Best First'.
Re: substitute a word in the whole file .. how ???
by kesterkester (Hermit) on Aug 13, 2003 at 14:34 UTC
    gbj and dbwiz's solutions are more elegant, but if you want it inside an existing script, you could use something like this:
    #!/usr/bin/perl use warnings; use strict; my $file = "txtfile"; # Read the file into $old_text: # open my $old_fh, "<$file"; my $old_text; do { local $/; $old_text = <$old_fh> }; close $old_fh; # Do the substitution # ( my $new_text = $old_text ) =~ s/\bfrog\b/toad/g; # Write the new "toad" data out, overwriting the old file # open my $new_fh, ">$file"; print $new_fh $new_text; close $new_fh;