Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

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

by dbwiz (Curate)
on Aug 13, 2003 at 11:28 UTC ( #283508=note: print w/ replies, xml ) Need Help??


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

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.


Comment on Re: substitute a word in the whole file .. how ???
Download Code
Re: Re: substitute a word in the whole file .. how ???
by star7 (Novice) on Aug 13, 2003 at 12:40 UTC
    I don`t want save the old file, and the commands must be in a perl-script.
    is
    s/frog/toad/g txtfile
    enough ??? star7
      s/frog/toad/g txtfile
      won't work inside a perl script. It works from the command line because "txtfile" is actually be handed to the mini-script created by using 'perl -i.bak -pe 's/frog/toad/g'. Use 'perl --help' to see what -i -p and -e mean. This sounds a lot like a homework assignment, but here is one solution:
      #!/usr/bin/perl -w use strict; # this script will edit itself ReplaceStuff($0,'word','taco'); sub ReplaceStuff{ my ($file,$origword,$newword) = @_; local $^I=""; # set the backup tag to nothing local @ARGV = $file; # make a local @ARGV so we can use <> # go through each line and do the substitution while (<>) { s/$origword/$newword/g; print; # print stuff out } }
        It's worth noting that you can put those command line arguments in the hashbang at the head of the script, e.g.
        #!/usr/bin/perl -w -i.bak -p s/frog/toad/g;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://283508]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (16)
As of 2014-11-25 21:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (158 votes), past polls