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

Somewhere recently I saw code that does an in-place edit of files and generated backups of the original files. Most likely I saw the code snippet in the Lama or the Camel, but it may have been here. Now I have a use for the technique, but I can't find the code. Can anyone help please?

Food for thought, not fuel for flames.

Replies are listed 'Best First'.
Re: Lost in-place file edit code
by tlm (Prior) on Jun 08, 2005 at 05:53 UTC

    You can achieve within a program the same effect as with the -i command line switch, by setting the perlvar $^I to the value of the backup extension. For example, the following snippet upper-cases the contents of the files foo.txt and bar.txt in place, and puts backup copies in foo.txt.bkp and bar.txt.bkp (note that there is no explicit open):

    use strict; use warnings; $^I = q(.bkp); @ARGV = qw( foo.txt bar.txt ); print uc while <>; __END__
    Setting $^I above to the empty string, causes foo.txt and bar.txt to be upper-cased in place, but no backups are created.

    the lowliest monk

      Thank you. That was what I was looking for.

      Food for thought, not fuel for flames.
Re: Lost in-place file edit code
by davido (Cardinal) on Jun 08, 2005 at 05:22 UTC

    Like this?

    perl -pi.bak -e "s/ /_/;" infile.txt

    See perlrun. For an on-site reference, see Re: One Liners (warning, I wrote that node).


    Dave

    Updated: fixed '-e'

      Surprisingly I also had exactly the same deja vu type experience a couple of days ago. And as quoted above, the -p command loops through text executing the command you give, and printing the result. The -i specifies what extension you want to give to your backup files.

      My most recent attempt was a file that looked like this:

      #!/usr/bin/perl -i.orig -p s/submit_(.*?)_/submit\u$1/g;

      I love the way you can specify command line arguments on the hash-bang line. The code above used the in-place capitalisation regexp operator discussed in another recent node (Regexp matched part to lower case).

      Nope, it was a few lines of code. Although I seem to remember seeing that described in the same context.

      Food for thought, not fuel for flames.

        Hi,

        You might of seen it in FMTYEWTK About Mass Edits In Perl or perlrun

        HTH.

        Walking the road to enlightenment... I found a penguin and a camel on the way.....
        Fancy a yourname@perl.me.uk? Just ask!!!
Re: Lost in-place file edit code
by mirod (Canon) on Jun 08, 2005 at 05:20 UTC

    Are you looking for the -i option?

    From perldoc perlrun: