Conclusion - Page 5
July 16, 2001
Well, you've just had an introductory lesson in using Perl
regular expressions to replace strings in files. I hope that what
you've learned will be of help to you. In the next article in
this series, we'll learn more about other text processing
capabilities within Perl that will allow you to easily process
records or delimited files. I've also posted the full script
below for your convenience.
use strict;
use Getopt::Std;
use Cwd;
use vars qw($opt_f $opt_s $opt_r $opt_d $opt_R);
getopt('Rdfsr');
&Usage unless $opt_f && $opt_s && $opt_r;
my $dir = ($opt_d) ? $opt_d : getcwd;
&Usage unless -d $dir;
my @files=split(/ /,$opt_f);
&search_n_replace($dir,$opt_s,$opt_r,\@files);
sub search_n_replace {
my ($dir,$search,$replace,$files) = @_;
my @thesefiles = @$files;
for (my $i=0; $i < @thesefiles; $i++) {
$thesefiles[$i] = "$dir/$thesefiles[$i]";
}
while (my $file=<@thesefiles>) {
open(IN,$file);
open(OUT,">$file.$$");
my $changed = 0;
while (<IN>) {
s/$search/$replace/gi && ($changed = 1)
&& print "$file - Changed $search to $replace\n";
print OUT;
}
close(IN);
close(OUT);
($changed==1) ? rename("$file.$$",$file)
: unlink "$file.$$";
}
if ($opt_R) {
opendir DIR,$dir || die "Cannot open $dir: $!\n";
my @dirs = grep -d, map "$dir/$_", grep !/^\./,
readdir DIR;
closedir DIR;
foreach my $dir (@dirs) {
print "checking $dir\n";
&search_n_replace($dir,$search,$replace,$files);
}
}
}
sub Usage {
die "Usage:\n this2that.pl [-R] [-d <directory>]
-f 'filename(s)' -s 'search' -r 'replace'\n\n";
}
[The colored lines above are one line. They have been split for
formatting purposes.]
Replacing Strings in Multiple Files - Page 4
Weaving Magic With Regular Expressions
Processing Text with Perl Functions - Page 6
|