![]() |
![]() |
|
Search & Replace with PERLIf you have ever
wanted to change an email address on all your web pages, or update many
html files with new links, here is an excellent command line function
you can use. The first example will replace the first match on each page. The second example will replace ALL matches on each page. And, the third example will replace all matches, and ignore text cAsE.
perl -pi -e 's/wordToFind/replaceWithThisWord/' *.fileExtension perl -pi -e 's/wordToFind/replaceWithThisWord/g'*.fileExtension perl -pi -e 's/wordToFind/replaceWithThisWord/gi'*.fileExtension Please note, if you use cygwin, you should use "perl -pi.orig" wordToFind: Replace this text with the word you would like to replace in your document(s) replaceWithThisWord: Replace this text with the new words you would like to place in your document(s) i: the little "i" means to ignore text case. Any combination of capital letters or lower-case letters will match. g: This little g means global. Basically, this means that all instances of the wordToFind be replaced on the page. If you do not put the little g in the expression, you will only replace the first wordToFind on each page. The rest will be unchanged. *.fileExtension : Replace this with the file extension of all the files you would like to search. Or replace the entire portion with the name of one file. The * is a wild card. This command uses regular expressions. So, as it is above, it can only be used to search and replace one word. However, if you want to get creative, and know a bit about regular expressions, you can do a lot with this simple line of code. For example, I recently updated a site I have so that all the links on the site were changed to remove the "www" portion of a particular address. Below is the code I used. It went through ALL the html files in the directory I was currently in, and replaced all instances of "www.keyedhosting" with "keyedhosting" . So, when you visited the site, all the links would now be http://keyedhosting.com instead of http://www.keyedhosting.com perl -pi -e 's/www\.keyedhosting/keyedhosting/' *.html Notice the backslash before the period. This is necessary to make it work. You use the backslash to "escape" symbols that have a particular meaning. But that is part of regular expressions, a topic that fills books up. Here is another example:
The above example illustrates how you can use the number sign instead of the forward slash. It is actually easier to use this method if you might be searching for a string that has a forward slash in it. It also illustrates the fact that you can look for small sentences this way. In this example, "this small sentence has a / in it" would be replaced with "a better sentence". So, go make a back up of your files and practice! |
|