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

This node falls below the community's minimum standard of quality and will not be displayed.
  • Comment on Re: Re: substitute a word in the whole file .. how ???

Replies are listed 'Best First'.
Re: Re: Re: substitute a word in the whole file .. how ???
by fletcher_the_dog (Friar) on Aug 13, 2003 at 14:11 UTC
    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;