#!/usr/local/bin/perl
#######################################################
# SEARCH AND REPLACE UTILITY
#
# call this script on the commandline with a single filename
#  and it will search for the searchstring and replace it 
#  with the replacestring
# It rewrites the searched file in place if there was a change
#  by copying the changed file in /tmp over the original
#
# call it in a cshell on multiple files like this:
#
# foreach i (*.txt)
# snr IN OUT $i 1
# end
#
# Be careful to make the search string unambiguous
# Store this program in your local bin directory
# set 755 permissions on snr
#
# You can even replace special characters by using the 
#  standard backslash escape character
#
# params searchstring replacestring filename [verbose]
#
# Set verbose to nonblank/nonzero to print a dot per replacement
#
# You are free to use this program as-is or modified,
# without restriction. Please add a link
# from your website to  http://perlcity.com/
#
# Copyright (c) 2002,2003,2004 Perlcity.com
#######################################################
#! /usr/bin/perl

$tmpdir = "/tmp";
$outfile = "$tmpdir/snr.$$";
$changed = 0;
$verbose = 0; # set verbose to 1 if you want it to print what its doing.

die "Usage: snr searchstring replacestring filename verbose\n\n" if ($#ARGV < 2);
$srch  = $ARGV[0];
$repl  = $ARGV[1];
$fname = $ARGV[2];
$verbose = $ARGV[3];

$verbose = "" unless($verbose);
$verbose = "." if($verbose);

# protect any metacharacters in either string
$srch =~ s/(\W)/\\$1/g;
$repl =~ s/\\n/\n/g;

print ":$fname:$srch:$repl:\n" if($verbose);

open(INFILE, $fname) || die("Can't open INFILE $fname");
print("$outfile\n") if($verbose);
open(OUTFILE, ">$outfile");
while(<INFILE>)
{
   s/$srch/$repl/og,$changed=1,print($verbose) if( /$srch/o );
   print(OUTFILE $_);
}
close(INFILE);
close(OUTFILE);

`mv $outfile $fname` if ($changed);
unlink($outfile) if ( -f $outfile);




# Please add a link from your website to  http://perlcity.com/
#
# <a href="http://perlcity.com/">Perl Books</a>
#