#!/usr/bin/perl # start at the top if($#ARGV<1) { print "Usage: replace \n"; exit(-1); } $newbuff=pop(@ARGV); $oldbuff=pop(@ARGV); &dodir(".",0,$oldbuff,$newbuff); sub dodir { local($dir,$nlink,$old,$new)=@_; local($dev,$ino,$mode,$subcount); # at the top level, we need to find nlink ourselves ($dev,$ino,$mode,$nlinks)=stat('.') unless $nlink; # get the list of files in the current directory opendir(DIR,'.'); local(@filenames)=readdir(DIR); closedir(DIR); if($nlinks==2) # this dir has no subdirs. { for(@filenames) { next if $_ eq '.'; next if $_ eq '..'; next if /^\./; print "$dir/$_\n"; if(!-d) { &replace($_,$old,$new); } } } else # this dir has subdirs. { $subcount=$nlinks-2; for(@filenames) { next if $_ eq '.'; next if $_ eq '..'; next if /^\./; $name="$dir/$_"; print "$name\n"; if(!-d) { &replace($_,$old,$new); } next if $subcount==0; #seen all the subdirs? # get link count and check for directories... ($dev,$ino,$mode,$nlink)=stat($_); next unless -d _; # it is really a directory, so do it recursively chdir $_ || die "can't cd to $name"; &dodir($name,$nlinks,$old,$new); chdir '..'; --$subcount; } } } sub replace { local($fil,$old,$new)=@_; open(handle,"<$fil"); open(h2,">$fil.tmp"); local($count); $count=0; while() { if(/$old/) { $count++; } s/$old/$new/; print h2; } print " $count occurences found.\n"; rename("$fil.tmp", $fil); }