perl global search replace many files
Issue:
Your ssh'd into a remote *NIX box and you have many files (potentially, in many directories) that need a 'minor' text change. (i.e. a simple search/replace)
For example, you want to change an variable name, 'MyVariable' to 'OurVariable'
here is a quick and dirty (careful, very dirty, there is no 'undo' on this, test first! - you have been warned)
$ find . -type f -exec perl -pi -e 's/ReplaceThisString/WithThisString/g' {} \;
this example finds any file under the current dir (and recursivly, through every dir under this path) and does an 'in place edit' of the file replacing 'ReplaceThisString', 'WithThisString'
For instance, recently I had to add binmode(\*STDOUT, ":utf8"); to a bunch of old perl/cgi scripts. I did so like such:
(note necessary escaping; and added comment)
perl -pi -le 's/charset\(\"utf-8\"\);/charset\(\"utf-8\"\);\nbinmode\(\\*STDOUT, ":utf8"\);\# re: 2105 \(db utf8\)/g' *.cgi
The above reads, find: charset("utf-8"); and replace it with: charset("utf-8");(i.e. itself (we need a pattern to find and this appears at the top of the scripts) and)
[Newline]binmode(\*STDOUT, ":utf8");
this combines the find comand (you can use all the functionalty of find) with the power of perl.
enjoy
