Friday, March 27, 2009

Perl Search and Replace an Entire Directory Tree

I recently had to do a search/replace for a couple of directories here at work. I know you're probably thinking why didn't I just do a find | xargs sed, well good point, though there is actually more to the code that is not displayed that worked better in perl. So ha! ;)

Anyhow, my code utilizes File::Find. If you've never used it, check it out. It's very useful. The process is easy; use find for a directory root and write a sub to process against the files.

Nothing too fancy here, but if you don't understand anything feel free to shoot me a message.

Cheers!


use strict;
use File::Find;

my $dir = "/mnt/www";

find(\&doFile, $dir);

sub doFile {
my $file = $File::Find::name;
my $fdir = $File::Find::dir;
open (FILE, $file) or die "Couldn't open file: $file $!\n";
my @foundfiles;
while () {
if ($_ =~ /your_search_regex/)
{
print "found: $file\n";
push(@foundfiles, $file);
}
}
close(FILE);

foreach my $f (@foundfiles) {
my $replace = qq~/usr/bin/perl -pi -e 's,your_search_regex,your_replacement,g' $file~;
print "$replace\n";
system($replace);
}
}

No comments: