#!/usr/bin/env perl # AUTHOR: Kris Davidson # DATE: March 2008 # FUNCTION: # This script should allow an HTML file to be renamed then loop through all other files in the directory and # update the links in those files to refer to the new name. # It expects two alphanumeric parameters both ending .html and seperated by a space. # CONVENTIONS: # 1. Spaces instead of tabs # 2. Bracketing BSD and GNU # 3. Identation is 8 columns # TODO: # 1. Allow directory recursion? # 2. Code to be cleaned up / improved # MISC: # A note to the Perl-One-Liners, yes I'm aware that a chunk of the script could be reduced to something like: # perl -i -pe 'BEGIN { $from = shift @ARGV; $to = shift @ARGV; } s/$from/$to/g' # You may value obfuscation, I however do not. # # Pragmas/Best practice options # use warnings; use strict; # # Definitions (A bit C like I know, but I think it keeps the code readable and tidy) # my $changed; # A Security/safety consideration that indicates a files content has changed my $correct; # Holds argument validation my $fileHandler; # Holds the file currently being read/searched/changed my $newName; # The new file name my $oldName; # The old file name my $pool; # All files to be searched and updated my $usage; # Holds correct usage statement my @newFile; # Array that contains changes made # # Input validation # $usage = " Syntax: [Old file name] [New file name] Seperated by a single space with the .html extension included. \n"; # # Each argument must end with .html # if (defined $ARGV[0] && $ARGV[1]) { $correct = ($ARGV[0]=~ /.+\.html$/) & ($ARGV[1]=~ /.+\.html$/); } die $usage unless $correct; # # Argument passing # $oldName = $ARGV[0]; $newName = $ARGV[1]; # # Some validation and error checking # if ($oldName eq $newName) { die "\n [Old file name] and [New file name] are the same, no changes made\n\n"; } elsif (! -e $oldName) { die "\n [Old file name] does not exist, aborting\n\n"; } elsif (-e $newName) { die "\n [New file name] already exists, aborting\n\n"; } # # Rename file # rename ($oldName, $newName) or die "ERROR, could not rename file: $!\n"; while ($pool = <*html>) # Search through all HTML files in the current directory { open (FILE, "<", $pool) or die "$0: $pool: $!\n"; # Open a file from the HTML set found using explicit mode while ($fileHandler = ) # Copy from the HTML file to named variable { if ($fileHandler =~ s/$oldName/$newName/g) # Replace occurrences of the old name with the new name in each line { $changed = 1; } push (@newFile, $fileHandler); # Add changes to array } close (FILE); if ($changed) { open (NFILE, ">", $pool); # Open file for writing / replacing print (NFILE @newFile); # Write the constructed array to the file close (NFILE); # Close file / clean-up $changed = 0; } undef @newFile; # Erase the content of the array before moving to the next file }