This section displays 2 scripts. The first, replace.pl, replaces a string in a single file. The second script calls replace.pl for all files of a directory.
Note: create a copy of your directory before working with these scripts.
#!/bin/env perl
if( scalar( @ARGV) != 4)
{
print "\n./replace.pl fileName oldString newString flagReally \n";
goto finish;
}
if( ! -x "/usr/local/bin/vrsn")
{
print "\n vrsn does not exist \n";
goto finish;
}
my ( $fileName, $oldString, $newString, $flagReally) = @ARGV;
if( ! -r $fileName)
{
print " $fileName does not exist \n";
goto finish;
}
if( $flagReally)
{
system( "/usr/local/bin/vrsn -s $fileName");
}
@lines = `cat $fileName`;
if( $flagReally)
{
open( FH, ">$fileName");
}
my $no = 0;
foreach $line ( @lines)
{
my $oldLine = $line;
if( $line =~ s/$oldString/$newString/g)
{
print "line $no \n";
print " old: $oldLine";
print " new: $line";
}
if( $flagReally)
{
print FH $line;
}
$no++;
}
if( $flagReally)
{
close( FH);
}
finish:
The second script calls replace.pl for many files (all .c files of the directory):
#!/bin/env perl
my $oldString = "WWM";
my $newString = "exp_to_mw";
sub yesno
{
print "$_[0] y/[n]: ";
return (<STDIN> =~ /^(y|Y)$/);
}
my @files = `ls -1 *.c`;
foreach my $file ( @files)
{
chomp $file;
if( $file !~ /\.c/)
{
next;
}
my $ret = `grep $oldString $file && echo ok`;
chomp $ret;
if( $ret =~ /ok/)
{
if( yesno( "execute $file"))
{
system( "./replace.pl $file $oldString $newString 1");
}
else
{
goto finish;
}
}
}
finish: