#!/usr/pkg/bin/perl
 
# 'sr' Search & Replace
 
# Written by P. Lutus Ashland, Oregon lutusp@arachnoid.com 5/30/96
# This script processes text files, finds and replaces arbitrary strings
# Be careful with this script - it accepts wildcards and processes every
# text file
# that meets the wildcard criteria. This could be a catastrophe in the
# hands of the unwary.
 
if($ARGV[1] eq "") {
  print "usage: srchstr replstr file1 file2 etc. or wildcards (replaces
originals in place)\n";
  print   "alternate: -c file1 file2 etc for console input of search and
replace strings\n";
}
else {
  if($ARGV[0] eq "-c") {
    shift(@ARGV);
 
    print "Enter Search String:";
    $srchstr = <STDIN>;
    chop $srchstr;
 
    print "Enter Replace String:";
    $replstr = <STDIN>;
    chop $replstr;
  }
  else {
    $srchstr = $ARGV[0];
    $replstr = $ARGV[1];
    shift(@ARGV);
    shift(@ARGV);
  }
  $totrep = 0;
  $totfil = 0;
  foreach $filename (@ARGV) {
    if(-T $filename) {
      $totrep += &process($filename);
      $totfil++;
    }
  }
  print "$totfil files, $totrep replacements\n";
}
 
sub process {
  $fn = $_[0];
  undef $/; # so we can grab the entire file at once
  print STDERR "$fn"; # show current file name
  open (INFILE,$fn);
  $q = <INFILE>;
  close INFILE;
 
  $/ = "\n"; # restore default
  $sum = 0; # force numeric interpretation of this variable
  $sum = ($q =~ s/$srchstr/$replstr/ig); # case-insensitive and global
 
  if($sum > 0) { # no point replacing file that isn't changed
    open (OUTFILE,">$fn");
    print OUTFILE $q;
    close OUTFILE;
    print " $sum replacement(s)";
  }
  print "\n";
  return $sum;
} # sub process

