#!/usr/bin/perl # allfiles.prl == useful to change things files below a point in directory tree # # crude perl script to find a piece of text ($from_text) # in files of a certain filename format ($file_glob) # in a specified directory ($start_dir) or any subdirectory below that # program replaces occurrences of that text with a specified replacement # ($to_text) # $case_sens chose case sensitive or insensitive search # $verbose sets level of output # $verbose = 0 gives total count only # $verbose = 1 gives count of lines changed per file # $verbose = 2 says as it processes each file (excessive) # allfiles.prl copyright claimed by Chris Evans (C.Evans@sghms.ac.uk) -- June 1996 # You're welcome to redistribute or use this file as you like provided that you # a) don't make a profit out of it # b) don't remove this copyright declaration # You may change the file for your own use as much as you like, but # if you give that changed version to others please let me know: # a) what you changed and why (I write bad code and am happy to incorporate # improvements with acknowledgements) # b) whether you are keeping acknowledgement to me (I'd like it!!!) # c) whether you plan to make money out of it (highly unlikel I'd say!!!) $start_dir = "."; # where to start find finding files $file_glob = "*.ht*"; # target files to process $from_text = "mailto:sgju101\@sghms.ac.uk"; # string to change $to_text = "http://www.psyctc.org/cgi-bin/mailto.pl?webmaster"; # what to change it to $case_sens = 0; # 1 for case sensitive, 0 for not $trusting = 1; # 1 if you will allow backup files to be deleted after changes $verbose = 1; # 0 - summary only, 1 tells you which files it's changed, 2 is too much! $bak = ".bak"; # backup extension # now run through all subdirectories looking for files print "find $start_dir -name $file_glob -print\n"; open(FIND, "find $start_dir -name \"$file_glob\" -print |") || die "Couldn't run find: $!\n"; if (!FIND) { print "\n\nNo files matching $file_glob found in or below $start_dir\n\n"}; while ($filename = ) { chop($filename); print "\nProcessing file: $filename...\n" if ($verbose == 2); $backname = $filename . $bak; rename($filename, $backname) || die "Couldn't rename $filename as $backname\n"; open (NEW, ">$filename") || die "Couldn't open new file as $filename\n"; open (OLD, "$backname") || die "Couldn't open $filename\n"; $changed = 0; while () { if ($case_sens) { $changed++ if s/$from_text/$to_text/g; } else { $changed++ if s/$from_text/$to_text/gi; } print NEW; } close NEW; close OLD; if (!$changed) { unlink($filename) || die "Couldn't delete empty $filename file\n"; rename($backname, $filename) || die "Couldn't rename $backname back to $filename\n"; } else { if ($changed > 1) { print "$changed lines changed in $filename\n"; } else { print "One line changed in $filename\n"; } if ($trusting) { unlink($backname); } } }