Here’s the ‘rename.pl’ script I mentioned in Ep. #56, originally written my Tom Christiansen and Nathan Torkington in “The Perl Cookbook” (Chapter 9.9, Renaming Files, O’Reilly, 1999)
#!/usr/local/bin/perl# Usage: rename perlexpr [files]
($op = shift) || die “Usage: rename perlexpr [filenames]\n”;
if (!@ARGV) {
@ARGV = ;
chop(@ARGV);
}
for (@ARGV) {
$was = $_;
eval $op;
next if (-e $_);
die $@ if $@;
rename($was,$_) unless $was eq $_;
}
Note: I added the 3rd line in the for loop, “next if (-e $_);” to prevent clobbering already existing files.
Some common cases where I use this:
- rename.pl ‘tr/A-Z/a-z/’ *
- rename.pl ‘s/\s/_/g’ *
- rename.pl ‘s/\.jpeg$/\.jpg/i’ *.jpeg
- rename.pl ‘s/_(\d)\./_$1\./’ *
- rename.pl ‘s/.xvid//i’ *
- rename.pl ‘s/.hdvt//i’ *
- rename.pl “s/\’//” *
- rename.pl ‘s/\”//’ *
- rename.pl ‘s/[\s,_]//’ *
- rename.pl ‘s/\”//’ *
Lowercase all filenames:
Change spaces to underscores:
Change JPEG to jpg:
Zero pad numbers in filenames (ie. ‘blah_1.jpg’ to ‘blah_01.jpg’):
Clean up pesky downloads:
Clean up filenames: