Using Perl to change file names
I run into the situation of having to rename so often that I am constantly tweaking my solution. Here I had to remove some extraneous characters on file names that a client had added. All we wanted where the first characters that started with DSFC and then the 4 digits. I had to drop off all the characters after that except for a possible optional a, b or c. then everything else had to drop except the .jpg at the end. Using perl’s regular expressions was the right tool for the job. In this case I copied the files to a new folder. You can easily just change the names right over top of the files by using the rename command instead of copy and use the same outupt directory as input. You can comment out the copy statement and uncomment the print statement to verify your regexp is working correctly, before actually doing the rename or copy.
#!/usr/bin/perl -w
use File::Copy;
use constant SOURCEPATH => “/Volumes/FireWire 58600/VRCfolder/Avery/userImages3-28-06/support team pix Folder/”;
my @files;
my $subfile = “renamed/”;#open and read the directory, copy the file names
#into an array, excluding files that begin with .
opendir (SOURCEDIR, SOURCEPATH) or ¬
die “Can’t open sourcedir ” . $!;
my @comprehensivedir = readdir SOURCEDIR;
foreach my $file(@comprehensivedir){
if (-f SOURCEPATH.”$file”){
push (@files, $file) unless $file =~ /^\./;
}
}#iterate through the files and copy them to
#a new directory, with the new name
#insert a print command to test it first.
#I have left a print command commented out that can be used
foreach my $file(@files){
my $newname = $file;
my $regExp = “(DSCF[0-9]{4}[bc]?).*(.jpg)”;
$newname =~ s/$regExp/$1$2/i;
copy SOURCEPATH.$file, SOURCEPATH.$subfile.$newname ¬
or warn “rename “. ¬
SOURCEPATH.”$file to” . SOURCEPATH.$subfile.”$newname ¬
failed: $!\n”;
#print SOURCEPATH.”$subfile$newname”.”\n”;
}
This perl script renamed over 100 files in less than a minute. Renaming the files manually would have taken me a good 15 to 20 minutes.