Monday, September 20, 2010

Search & replace text in multiple files in Unix

To search a particular string in multiple files and replace all occurrences with a new string, you can use the following handy Perl one-liner:

perl -pi -e 's#search_string#replace_string#g' *.php

Here, the -p switch wraps the script inside a loop, executing once for each input file which is denoted by the last arguement *.php.

The -i switch allows inline modification of the file; you can optionally save a backup of the original file by providing the backup file name template after this switch as -i *.bak.

The -e switch executes the following piece of code.

The string of code 's#search_string#replace_string#g' searches for search_string and replaces it with replace_string globally. You can use any other character like "/" to delimit the search & replace strings. Remember to replace the place-holder text with the actual text and also escape it properly.

No comments:


Related Posts Plugin for WordPress, Blogger...