#!/bin/perl5 -w # $Id: subst,v 1.2 1999-09-27 13:05:38-05 annis Exp $ # $Source: /u/annis/uw-unix/perltut/RCS/subst,v $ # # Do a search and replace of all given files. # ./subst /old/new FILE-0 FILE-1 ... FILE-N use POSIX; use strict; # Get the replacement pattern: /old/new/ my $regexp = shift @ARGV; # First, grab out the pattern. my @rtmp = split(/\//, $regexp); if ($#rtmp != 2) { die "Where is my regular expression?"; } my $old = $rtmp[1]; my $new = $rtmp[2]; # We're going to keep all files in this temporary my $temp = tmpnam(); # MAIN loop foreach my $file (@ARGV) { if (! open(FH, "< $file")) { print STDERR "I can't open $file: $!\n"; exit(1); } else { open(NEW, "> $temp") or die "Can't open $temp"; my $move = 0; # False while () { if ($_ =~ s/$old/$new/g) { $move = 1; } print NEW $_; } close FH; close NEW; if ($move) { rename($file, "$file.bak") or die "Cannot rename $file"; `mv $temp $file`; # rename can't cross filesystems #rename($temp, $file) or die "Cannot copy $temp to $file: $!"; } } } unlink($temp) or die "Unable to remove $temp: $!"; # EOF