Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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

by star7 (Novice)
on Aug 13, 2003 at 11:14 UTC ( #283505=perlquestion: print w/replies, xml ) Need Help??

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

This node falls below the community's threshold of quality. You may see it by logging in.
  • Comment on substitute a word in the whole file .. how ???

Replies are listed 'Best First'.
Re: substitute a word in the whole file .. how ???
by dbwiz (Curate) on Aug 13, 2003 at 11:28 UTC
    perl -i.bak -pe 's/frog/toad/g' txtfile

    This one-liner will save your old file into txtfile.bak, and modify txtfile by changing every occurrence of "frog" into "toad".

    See perlrun for details on the command line arguments.

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: substitute a word in the whole file .. how ???
by gjb (Vicar) on Aug 13, 2003 at 12:06 UTC

    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-

      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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://283505]
Approved by cchampion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2022-01-19 09:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (55 votes). Check out past polls.

    Notices?