Archive

Posts Tagged ‘Scripts’

How To: Search and replace across files on Windows using Perl

December 27th, 2008

This may seem redundant, but the reason I am posting this is because there are several examples on the web on how to do this on Linux - but not on Windows. Here is how to do it effectively on Windows.

Say, for example, it is the new year and you want to change the copyright on all your html files from 2008 to 2009.

First, you need to make sure you have a perl distribution installed on Windows. It comes installed by default on Linux but not on Windows. You can try ActiveState Perl, but I recently had problems downloading from their site and came across Strawberry Perl, which works great!

Next, change into the directory in which you need to change files.

perl -pi.bak -e “BEGIN{@ARGV=<*.SUFFIX>} s/FIND/REPLACE/g”

This command does the following:

  • -p tells perl to loop over the files in the directory
  • -i.bak tells perl to create a backup of all the changed files
  • -e means execute the following code

A windows example:

perl.exe -pi.bak -e "BEGIN{@ARGV=<*.html>} s/-2008/-2009/g"
This will search for "-2008" and replace it with "-2009"

Just for reference, to do this on Linux is slightly easier… for example:

perl -pi.bak -e "s/2008/2009/g" *.html

Use at your own risk!

How To , ,