|
Have you ever been in a situation where you have to replace
one or two words in many text files. As a programmer or system
administrator I'm sure you have been in a situation when even
Emacs' search and replace command feels like doing a lot of
repetitive tasks. This small tutorial will show the power
of Perl with just a line of code.
Here I will give some examples of how you can use the Perl
command line to do quick and dirty search and replace jobs.
If you want to know more about regular expressions read the
article: Regular Expressions Explained.
In the first example we take the file file.txt and replace
every occurrence of OldText with the text NewText.
$ perl -pi -e s/OldText/NewText/g file.txt
If you have several text files and want to replace some text
in them you could use the powerful find command. The Perl
code below shows how you can replace a text in every file
called .conf.
$ perl -pi -e s/OldText/NewText/g `find . -name "*.conf"`
A Real Life Example
Let's say you make a local copy of a web site. But when
you try to browse it none of the links and images work. They
all refer to http://asite.com/some/path/.
You then want to remove every occurrence of http://asite.com/
to make the links relative. Perl makes this possible with
a simple command.
The command below will remove every occurrence of a http://
reference and let the relative path part stay. E.g. http://zez.org/images/logo.png
will be replaced with images/logo.png, this will enable local
browsing of the site.
$ perl -pi.bak -e s#http://.*?/##g `find . -name "*.html"`
Remember to quote
If you are matching a text like "a text" and
get an error like: Substitution pattern not terminated at
-e line 1. . This is because of the spaces in the text. If
you quote the regexp it works fine. The example below shows
how to use a regexp with spaces.
$ perl -pi.bak -e "s#a text#another text#g" text.txt
What If I Mess Up?
If you're not familiar with regular expressions or just
want to be on the safe side you should make backups. This
is easily done with the -pi parameter. If you write -pi.bak
the original files are saved as .bak. This way you won't loose
any data, and that's nice. Better to be safe than sorry.
When you want to delete the backup files just do a rm like
the example below. Warning: this is a destructive delete.
$ rm -f `find . -name "*.bak"`
Author: Bård Farstad ZEZ.org
Zez is a community website for developers, graphics and content
designers. We aim to satisfy the intermediate to expert developers.
For more information please visit www.zez.org
|