#!/usr/bin/perl -w
#
# Usage:  replace.pl original_string replacement_string input_filename
# This Perl script changes the string $original to $replacement in all files
# specified on the command line.
# 19950926 gkj
$original=$ARGV[0];
$replacement=$ARGV[1];
# The input record separator is defined by Perl global
# variable $/.  It can be anything, including multiple
# characters.  Normally it is "\n", newline.  Here, we
# say there is no record separator, so the whole file
# is read as one long record, newlines included.
undef $/;

$file=$ARGV[2];

if (! open(INPUT,"<$file") ) {
    print STDERR "Can't open input file $bakfile\n";
    exit(0);
}

# Read input file as one long record.
$data=<INPUT>;
close INPUT;

if ($data =~ s/$original/$replacement/gi) {
    $bakfile = "$file.bak";
    # Abort if can't backup original or output.
    if (! rename($file,$bakfile)) {
	die "Can't rename $file $!";
    }
    if (! open(OUTPUT,">$file") ) {
	die "Can't open output file $file\n";
    }
    print OUTPUT $data;
    close OUTPUT;
    print STDERR "$file changed\n";
}
else {
    print STDERR "$file not changed\n";
}

exit(0);
