#!/usr/bin/perl -w # gsr.pl # Global Search and Replace # Script to recursively search for a string and replace (or delete) it. # Last Modified: October 2006 use strict; die "Usage: perl gsr.pl [option] toplvldir searchstring replacestring\n \t-svn Check in files before modification\n \t-dirty Keep unmodified files as fileName.orig\n" unless $ARGV[1]; my $svn; my $dirty; # check for any options while ($ARGV[0] =~ /^-/) { $svn = shift @ARGV if $ARGV[0] eq "-svn"; $dirty = shift @ARGV if $ARGV[0] eq "-dirty"; } my ($dir, $search, $replace) = @ARGV; # get the arguments $replace = "" unless defined($replace); #if no replacement is given, define $replace so Perl will delete $search print "I will search <$dir> for <$search> and replace it with <$replace>.\n\n"; chomp(my @files = `grep -ril $search $dir`); # let Grep do the dirty work, and remove new line characters unless (@files) { print "$search doesn't appear in any files! Bye, now.\n"; exit; } @files = sort @files; # put any hidden directories in the front while ($files[0] =~ /.*\.svn.*/){ # get rid of any .svn dirs shift @files; } print "<$search> appears in:\n"; if (@files) { foreach (@files) { print "\t$_\n"; } print "Shall I replace? (y/n): "; } chomp(my $continue = ); # continue? if ($continue =~ /^y/i) { system "svn ci -m \"GSR script checking in files before replace\" @files" if $svn; # check in the files if -svn sleep(5) if $svn; # wait for svn to work (yeah, I should probably do this another way) foreach (@files) { my $orig = "$_.orig"; rename $_, "$orig"; # move file to file.orig open INPUT, "< $orig" or die "cannot open $_.orig for input: $!\n"; open OUTPUT, "> $_" or die "cannot open $_ for output: $!\n"; print "\tReplacing in $_\n"; while () { # do the replacement s/$search/$replace/g; print OUTPUT "$_"; } close OUTPUT; # aren't I nice? close INPUT; unlink $orig unless $dirty; #delete the originals unless the user says no } } else { print "Well, aren't you a waste of my time.\n"; }