| 1 | #!/usr/bin/perl
|
|---|
| 2 | use File::Temp;
|
|---|
| 3 |
|
|---|
| 4 | sub substitute {
|
|---|
| 5 | my($oldstring) = $_[0];
|
|---|
| 6 | my($newstring) = $_[1];
|
|---|
| 7 | my($filename) = $_[2];
|
|---|
| 8 | my($line);
|
|---|
| 9 | my($found) = 0;
|
|---|
| 10 |
|
|---|
| 11 | my($tmpfile) = "PERLSUBTMPFILE";
|
|---|
| 12 | open(OLDFILE, "<$filename") || die "Could not open $filename";
|
|---|
| 13 |
|
|---|
| 14 | while (!$found && defined($line=<OLDFILE>)) {
|
|---|
| 15 | if ($line =~ /$oldstring/) {
|
|---|
| 16 | print "String found in $filename: $line";
|
|---|
| 17 | print "Substituting within this file\n\n";
|
|---|
| 18 | $found = 1;
|
|---|
| 19 | }
|
|---|
| 20 | }
|
|---|
| 21 | close(OLDFILE) || die "Could not close $filename";
|
|---|
| 22 |
|
|---|
| 23 | if ($found) {
|
|---|
| 24 | open(OLDFILE, "<$filename") || die "Could not open $filename";
|
|---|
| 25 | open(NEWFILE, ">$tmpfile") || die "Could not open $tmpfile";
|
|---|
| 26 | while (defined($line=<OLDFILE>)) {
|
|---|
| 27 | $line =~ s/$oldstring/$newstring/g;
|
|---|
| 28 | print NEWFILE $line;
|
|---|
| 29 | }
|
|---|
| 30 | close(OLDFILE) || die "Could not close $filename";
|
|---|
| 31 | close(NEWFILE) || die "Could not close $newfile";
|
|---|
| 32 | unlink($filename) || die "Could not delete $filename";
|
|---|
| 33 | rename $tmpfile, $filename || die "Could not rename $tmpfile to $filename";
|
|---|
| 34 | }
|
|---|
| 35 | }
|
|---|
| 36 |
|
|---|
| 37 | $numargs = $#ARGV + 1;
|
|---|
| 38 | # print "num args is $numargs\n";
|
|---|
| 39 | # print "arg0: $ARGV[0]\t arg1: $ARGV[1]\n";
|
|---|
| 40 | die "At least 3 arguments required: old string, new string, one or more file names"
|
|---|
| 41 | unless $numargs >= 3;
|
|---|
| 42 | foreach $file (@ARGV[2..$#ARGV]) {
|
|---|
| 43 | printf("Examining file $file...\n");
|
|---|
| 44 | &substitute($ARGV[0], $ARGV[1], $file);
|
|---|
| 45 | }
|
|---|
| 46 | 1;
|
|---|