| CLI: Insert/Replace Text in Multiple Files |
|
|
|
| Tech Notes - Linux | ||||
| Written by Rick | ||||
| Friday, 12 December 2008 09:43 | ||||
|
 For the past day or so I've been working through issues to add/change or delete strings in multiple files. As usual there is plethora of methods to do try. Each have a place in an administrator's arsenal. Using Perl or SEDThese methods are suited for text manipulation where search and replace strings are simple without the need for escape characters; In the following example we replace the word rabbit with the word blueberry in all html files in the current directory;
Of course, there are an abundance of switches that can be used to accomplish more tasks like backing up files before actually executing the search replace function. Check the man pages for more details. Using RPLRPL on the other hand I found very useful. In Ubuntu Linux RPL can be installed from the repositories and I suspect other flavors of Linux can too. Otherwise, you can go the RPL site http://www.laffeycomputer.com/rpl.html. I found RPL very handy when executed in a shell script to replace hugh strings on multiple lines with many escape characters. My immediate need was to remove text from 200+ files in multiple subdirectories without hand editing each file. This is where it gets cool;
As you can see there are many characters in the code I needed to delete that require insertion of escape characters to make it work with sed, cat, or perl. In this case the script works great, but then there are no ['] characters in the text to be searched. That'll become a challange to overcome one day when needed. RPL command explained;
Part of this gets a little confusing. The usage of the -x switch and specifing the filename at the end. Multiple -x switches can be used to change mutiple file extensions in the same pass. Not using the - x switch and attempting to specify *.htm (for example) seems to limit RPL to a single directory. To get recursive to work the -x switch was required with a wildcard mask at the filename location. Another great resource for text editing commands is IBM. |




