Replace a word in all text files in a directory
Saturday September 02nd 2006, 9:48 pm
Filed under: Tips & Trik

#!/usr/bin/perl
# A utility to replace substrings in all text files in a directory
# copyright 1999, M. David Green
# http://www.greenthing.com/
#
# Usage: replacer.pl directory oldstring newstring
#

if (($ARGV[0] eq “”) || ($ARGV[0] eq “?”)) {
print “A utility to replace substrings in all text files in a directory\n”;
print “Usage: replacer.pl path oldstring newstring\n”;
end;
} else {
$directory = $ARGV[0];
$oldstring = $ARGV[1];
$newstring = $ARGV[2];
$directory = $directory . “\/” unless ($directory =~ /\/$/);
print “Directory is $directory\n”;
print “Old String is $oldstring\n”;
print “and Replacement String is $newstring\n\n”;
#
opendir (DIR, $directory);
@files = readdir(DIR);
closedir (DIR);

foreach $file (@files) {
$fullpath = $directory . $file;
open (FILE, $fullpath);
@thisfile = ;
close (FILE);
foreach $line (@thisfile) {
$line =~ s/$oldstring/$newstring/g;
}
open (FILE, “>$fullpath”);
foreach $line (@thisfile) {
print FILE $line;
}
close (FILE);
print “$fullpath scanned\n”;
}
print “Done\n”;
end;
}


No Comments so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

(required)

(required)