in reply to "Updating" files.

perl -p -i.bak -w -e 's/dude/Johnny5/g' myinfo.txt

The most confusing part of this is probably all those switches. Take a look at perlrun for help (the following instructions are directly from there).

The -p switch assumes the following loop around your program.

LINE: while (<>) { ... # your program goes here } continue { print or die "-p destination: $!\n"; }

As you can see, it looks like the body of your perl program.

The -i switch specifies that files processed by the <> construct are to be edited in-place. It does this by renaming the input file, opening the output file by the original name, and selecting that output file as the default for print() statements. The extension, if supplied, is used to modify the name of the old file to make a backup copy.

You can see that in the one-liner, the new file's filename will be appended with '.bak'.

The -w switch is to turn on warnings. Simple enough.

The -e switch tells Perl to run any following code (which is between the apostrophes).

The substitution in the actual code is simply globally replacing all instances of 'dude' with 'Johnny5'. It is more vague than your regex, and it will replace all instances, not just the first one.

Finally, the filename at the end of the one-liner is the argument to the code.

In other words, that one liner can be rewritten in a file as:

#!/usr/bin/perl -w $extension = '.bak'; LINE: while (<>) { if ($ARGV ne $oldargv) { if ($extension !~ /\*/) { $backup = $ARGV . $extension; } else { ($backup = $extension) =~ s/\*/$ARGV/g; } rename($ARGV, $backup); open(ARGVOUT, ">$ARGV"); select(ARGVOUT); $oldargv = $ARGV; } s/dude/Johnny5/g; } continue { print or die "-p destination: $!\n"; }

Pretty cool, eh.

And you didn't even know bears could type.

Replies are listed 'Best First'.
Re^2: "Updating" files.
by neutron (Sexton) on Jan 25, 2009 at 22:48 UTC
    Thanks to all of you. I used the "long hand" sytle and it works like a charm.

    As for the "short hand", still can't seem to figure this one out. I've tried the command in ms-dos and in a pl file. Is it perhaps only a unix thing? If it helps to know, it does create the back-up file but gives the following error: "Useless use of a constant in void context at -e line 1."

    On that note, I feel like I'm totally missing out here. Should I be using unix to get access to perl's full potential. I know, what a newb question ...

      Try using double quotes instead of single quotes. And yeah, using Perl on unix feels more at home.

      And you didn't even know bears could type.

        Awesome! Thank you!!!