Since this is the third time in the last year I've had to look this up, I am making a note on my blog, where it should be easy for me to find :)
From this 'notes on Perl' page, how to inplace edit a file with perl:
perl -p -i.bak -e "s#a#b#" filename
| Flag | Meaning | |
|---|---|---|
| -p | Execute the command(s) for every line. | |
| -i.bak | Edit the given file in-place ".bak" is the extension name of the backup file. | |
| -e | Introduces the command to execute. The command in this case is 's' for substitute. |
See also perldoc.com for information on regular expression syntax and such.
Comments
And if you happen to have access to a regular unix tool chain, you can issue much the same command with sed:
sed -i.bak -e 's/a/b/' <file>
I suppose you could even alias sed to be 'perl -p' if you were feeling adventurous.
You can of course substitute your own favourite characters for '/' (or character pair, such as [], {} and <> if you're using perl).
Note that if your doing a command line search and replace, you probably want to use the g option on your regexp to make it a global search, rather than just the first.
Well, it depends which version of sed you have. With version 3.x (RedHat 2.1 Enterprise among others) you don't get in-place editing. That's why the sed FAQ recommends perl for this task. See http://www.faqs.org/faqs/editor-faq/sed/ at 4.4.1, which has a couple of different solutions, including, for older sed:
This does show the use of pipe chars and a global replace.
interesting bit, perl inplace editting only works witht he -p option, not the -n option, I would have thought the -p would produce output, but it appears that the printed lines go to the file being editted..
The *rpl* command is another alternative to perl and sed for editing a file.
rpl - intelligent recursive search/replace utility
One of the advantages of this program for new users is that it is more verbose than sed or perl about doing
these sorts of operations. (I have found this to be more welcoming for non-programmers.)
Quick Demo:
sgeiger@a31:~/demo$ echo "foo bar foobar" > temp.txt
sgeiger@a31:~/demo$ rpl -R -x'.txt' 'foo' 'bar' .
Replacing "foo" with "bar" (case sensitive) (partial words matched)
.
A Total of 2 matches replaced in 1 file searched.
sgeiger@a31:~/demo$
Common Options:
rpl -Ribdvsptw -x'.txt' 'foo' 'bar' .
-- That uses these options: recursive, case-insensitive, backup, keep modification times, verbose,
simulate replacement, prompt, use TMPDIR, match only on word boundaries
you can try to remember this by pie
perl -p -i -e