#!/usr/bin/perl -w # Script to make text replacements to a list of files # # The author of this script makes no warranty, # express or implied, that this script will # do anything useful at all, and any use # of it is entirely at your own risk. # # by Lev Koszegi 4/10/2006 use strict; use File::Copy; use File::Basename; use Cwd; usage() unless $#ARGV == 1; #Require two arguments (list file & pattern file) my (@files, @patterns); my ($pattern, $filename); my $now = time; my $dir = cwd; open FILE_LIST, $ARGV[0] or die "Cannot open file list: $!"; chomp(@files = ); #Test the lines of FILE_LIST to make sure files exist; #if not, note which one is bad and die. foreach $filename (@files) { die "Invalid file name ($filename): $!" unless -e $filename; } close FILE_LIST; open PATFILE, $ARGV[1] or die "Cannot open pattern file: $!"; #Test the pattern file to make sure it looks okay, or die. chomp(@patterns = ); foreach $pattern (@patterns) { #Pattern must begin with a forward slash, contain exactly three #unescaped forward slashes, and end with same plus optional g and/or i. unless ($pattern =~ /^\/.*[^\\]\/.*[^\\]\/(g|i|gi|ig)?$/) { die ": bad pattern: $@"; } #Create the substitution commands. $pattern = 's' . $pattern; } close PATFILE; #Create backup directory, timestamped to make it unique. my $bakdir = "bak_${now}"; mkdir $bakdir, 0755 or die "Cannot create archive directory: $!"; my $tarFile = $bakdir . '/' . "bak.tar"; my $logfile = $bakdir . '/' . "logfile"; #Create log file open LOG, "> $logfile" or die "Cannot create logfile: $!"; select LOG; $| = 1; # Don't keep LOG entries sitting in the buffer. select STDOUT; #Tarball the files to archive current state !(system "tar", "chvlf", $tarFile, "-I", $ARGV[0]) or die "Cannot create backup archive!"; print LOG "Created archive OK.\n"; !(system "gzip", $tarFile) or print LOG "Cannot compress archive; proceeding anyway.\n"; #Loop through each file and make the edit(s) foreach $filename (@files) { #Copy contents of file to a temporary work file. my $wkfile = $bakdir . '/' . basename $filename; copy($filename, $wkfile) or die "Cannot copy ${filename}: $!"; open(FILE2CHANGE, "<$wkfile") or die "Cannot open ${wkfile} for reading: $!"; open(UPDATED, ">$filename") or die "Cannot open ${filename} for writing: $!"; while () { #Run each substitution on the line. foreach $pattern (@patterns) { eval $pattern; } print UPDATED; } print LOG "Processed ${filename}\n"; close FILE2CHANGE; close UPDATED; unlink $wkfile; } close LOG; ################################### sub usage { die <