Podcasting What Geeks Really Want To Hear

Sunday, June 17, 2007

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:


    Lowercase all filenames:
    • rename.pl ‘tr/A-Z/a-z/’ *

    Change spaces to underscores:

    • rename.pl ‘s/\s/_/g’ *

    Change JPEG to jpg:

    • rename.pl ‘s/\.jpeg$/\.jpg/i’ *.jpeg

    Zero pad numbers in filenames (ie. ‘blah_1.jpg’ to ‘blah_01.jpg’):

    • rename.pl ‘s/_(\d)\./_$1\./’ *

    Clean up pesky downloads:

    • rename.pl ‘s/.xvid//i’ *
    • rename.pl ‘s/.hdvt//i’ *

    Clean up filenames:

    • rename.pl “s/\’//” *
    • rename.pl ‘s/\”//’ *
    • rename.pl ‘s/[\s,_]//’ *

posted by Nem W Schlecht at 15:25 in General    

24 queries. 0.421 seconds.