Code Example #5 – WinGrepReplace

In the day to day happenings of web development many of us get into binds and have problems getting out of them. Yesterday a good friend of mine came to me with a huge problem. Her website of more than 700 files needed to have certain entries replaced and the amount of time it would take to go through them all and replace the lines individually was not worth the effort. Thankfully she knows that i dont do anything that difficult by hand, i invent something to do the work for me and give my computer a smack on the butt and just wait for the results.

Here is the Perl code to do just that:

#!/usr/bin/perl -w
################################################################################
# WinGrepReplace
#
# Replace a given line in all files in a directory of files.
################################################################################

use File::Find;
use File::Copy;

die "Usage: $0 directory find [replace]"if (@ARGV > 3 || @ARGV < 2 ||
!-e $ARGV[0] || length $ARGV[1] == 0);

our ($dir, $find, $replace) = @ARGV;

find(&func, $dir);

sub func
{
   return if !stat || -d;

   open(FILE, "<$_");
   open(FILEO, ">$_.new");

   while (($line = ))
   {
       $line =~ s/$find/$replace/i if ($line =~ m/$find/i);
       print FILEO $line;
   }

   close FILE;
   close FILEO;

   move("$_.new", $_);
}

Although there are a couple of hacks and vulnerabilities in this block, it gets the job done nicely.