jefft 02/04/12 04:57:14 Added: tools/bin replace Log: Script to replace a block of text with another, in multiple files. Useful for making changes in multiple build.xml files. Revision Changes Path 1.1 jakarta-avalon-excalibur/tools/bin/replace Index: replace =================================================================== #!/usr/bin/perl -w # # Script to replace one multiline string with another in a list of files. # Typical usage: re "`cat fromfile`" "`cat tofile`" *.xml # Where fromfile contains the regexp, and tofile contains text to replace # each regexp match with # # Author: Jeff Turner <[EMAIL PROTECTED]> # Based on code at # http://www.cclabs.missouri.edu/things/instruction/perl/perlcourse.html sub usage() { print " $0: A script to replace one block of text with another in multiple files Usage: $0 <from> <to> [file...] Where <from> is a regex occurring in [file] <to> is a string which will replace each occurrence of <from> [file...] a list of files to act on.\n" } $original = shift(@ARGV) or &usage and exit; $replacement = shift(@ARGV) or &usage and exit; $nchanges = 0; # 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 $/; foreach $file (@ARGV) { if (! open(INPUT,"<$file") ) { print STDERR "Can't open input file $file\n"; next; } # Read input file as one long record. $data=<INPUT>; close INPUT; if ($data =~ s/\Q$original/$replacement/gs) { $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"; $nchanges++; } else { print STDERR "$file not changed\n"; } } print STDERR "$nchanges files changed.\n"; exit(0);
-- To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]> For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>
