Monday, May 24, 2010

Perl: One liner for Search and Replace in Multiple Files

Problem Statment:
Want to search a nd replace a string in multiple files? That to in one line? Simple! Read ahead..

Solution:
Install Perl and use Perl single line execution ie perl -e
Here's the actual statement taht will do the trick:

perl -pi -i.back -e 's///g;' *.txt

Explaination:
perl.exe is of course required for you to run the script.
-p : runs over the complete files.
-i : edits the files required.
-e : execute the script.
-i.bak : this creates a back-up of the file that is opened for editing.
*.txt : Search and Replace operation works on all files with extension '.txt'.

Small Tip: this is an important interview question. Adds more interest to the post, isn't it? :)

Hope this helps!

No comments: