#!/usr/bin/perl -w
# Copyright © 2002 by Julian Fong . All rights reserved.
#
# Permission to use, copy, modify, distribute, and sell this software
# and its documentation for any purpose is hereby granted without fee,
# provided that the above copyright notice appear in all copies and
# that both that copyright notice and this permission notice appear in
# supporting documentation. No representations are made about the
# suitability of this software for any purpose. It is provided "as
# is" without express or implied warranty.
#
# gsr: Global Search & Replace - it does just that on a list of files. Takes:
# -F: to completely ignore any magic in the patterns
# -i: case insensitivity in search pattern
# -v: verbose mode
use strict;
use Getopt::Std;
my (
$search,
$replace,
%options,
$sopt,
$filename,
$matched,
$scanned
);
getopts('ivF', \%options);
unless (@ARGV > 2) {
die "Usage: gsr [-ivF] search_pattern replace_pattern [files]\n"
}
$search = shift(@ARGV);
$replace = shift(@ARGV);
$sopt = "go";
if ($options{'i'}) {
$sopt .= 'i';
}
foreach $filename (@ARGV) {
$scanned = "";
$matched = 0;
open (IFILE, "$filename") || die ("Can't open file: $!\n");
# Scan for matching text, preserving the file in $scanned
# in the meantime.
while () {
if ($options{'F'}) {
last if ($matched = eval "m'$search'$sopt");
} else {
last if ($matched = eval "m/$search/$sopt");
}
$scanned .= $_;
}
if ($matched) {
if ($options{'v'}) {
print "Match: $filename\n";
}
rename($filename, "$filename~");
unlink($filename);
open (OFILE, ">$filename") || die ("Can't open file: $!\n");
# Print already scanned text
print OFILE $scanned;
# Do first replacement
if ($options{'F'}) {
eval "s'$search'$replace'$sopt; print OFILE";
} else {
eval "s/$search/$replace/$sopt; print OFILE"
}
# Scan and print remaining replacements
while () {
if ($options{'F'}) {
eval "s'$search'$replace'$sopt; print OFILE";
} else {
eval "s/$search/$replace/$sopt; print OFILE"
}
}
close OFILE;
} elsif ($options{'v'}) {
print "No match: $filename\n";
}
close IFILE;
}