#!/usr/local/bin/perl -s # # replace.pl # # Replace the old pattern with a new pattern in given source file! # Just edit the first line, if your perl executable sits on different # dir. You can find out the location with "which perl" command. # Run "replace.pl -h" to see more options. # # Last modified: 8/7/96 # Author: Bekman Stas # $0 =~ s/^.*\///; # cut the basename of the command # Diagnostic part... if ($#ARGV<2 || $h) { die "\nUsage: \t $0 [-options] old_pattern new_pattern original_file(s) options: -h You read me now -no_bak Don't backup the original file -no_glob If you want to replace only first occurence in each line -no_sens Case insensitive replace old_pattern single pattern without quotes or 'any exact sub sentence' new_pattern the same as old_pattern\n" } # Real program... # Remove the patterns from @ARGV, leave only filenames # Note: options stripped from @ARGV by "perl -s" flag !!! So we have only filenames $old=(shift @ARGV); $new=(shift @ARGV); # Store the original files' modes (Must do! Because of open(Bla,">foo") ) foreach (@ARGV) { $modes{$_}=(stat)[2]; } while (<>){ if ($ARGV ne $oldargv){ if (!$no_bak) {rename($ARGV, $ARGV . '.bak');} open (ARGVOUT, ">$ARGV") || die "Can't open $ARGV[0]: $!\n"; select(ARGVOUT); $oldargv= $ARGV; } (!$no_glob) && (!$no_sens) && (s/$old/$new/og) && next; (!$no_glob) && ($no_sens) && (s/$old/$new/ogi) && next; ($no_glob) && (!$no_sens) && (s/$old/$new/o) && next; ($no_glob) && ($no_sens) && (s/$old/$new/oi) && next; } continue { print; # this prints to the original filename } close(ARGVOUT); select(STDOUT); # Restore the original files' modes (Must do! Because of open(Bla,">foo") ) foreach (keys %modes) { chmod $modes{$_},$_; }