An easier way to search and replace in UNIX with perl (taken from http://www.shooter.net/index.php/weblog/Item/an-easier-way-to-search-and-replace-in-unix-with-perl/)
perl -pi -e 's/search/replace/g' *.text
Here's a breakdown of how that command works:
-p
Assumes an input loop around the script. It reads each line of the file and outputs it after processing
-i
Activates in place editing of files
-e
Indicates a single lines script
s/search/replace/g
is the script or command. In this case it's a search and replace regex (regular expression). Replace the “search” and “replace” with the text to be operated upon.
*.text the filename(s) to operate on
You can also say
perl -pi.bak -e 's/search/replace/g' *.text
The .bak
tells it to save unchanged copies with that extension.
Often one will search and replace a directory path which itself contains forwards slashes. This link explains how to do so within a regex:
http://www.coderetard.com/2008/11/11/sed-how-to-escape-forward-slash-with-the-right-delimiter/
The summary is:
In the regular expression, it’s not necessary to delimit the find and replace texts and search options with the slash ‘/’ character. In fact, you can use just about any character to delimit the expression:
% sed s#file:\/\/#http:\/\/#g *.txt % sed s@file:\/\/@http:\/\/@g *.txt % sed sAfile:\/\/Ahttp:\/\/Ag *.txt
Using #, @, and A as the delimiter will all work out to the same valid sed operation to find all strings of “file:” text and replace it with “http:” text.