Des (deskitty) wrote,
Des
deskitty

  • Mood:

Nifty Perlage

I had a shitload of Kyou Kara Maou eps that had messed-up filenames, so I wrote myself a nifty little Perl script that renames lots of files based on a (series of) regular expression(s) (actually, they can be arbitrary Perl statements that manipulate $_, but ssshhh ... don't tell anyone!).

I don't know how many times I've needed to do something like this, and I'm surprised I haven't found a UNIX tool that does this already.

#!/usr/bin/perl

use Getopt::Long;

my $help = 0;
my @regexps = ();
my $dryrun = 0;
my $verbose = 0;

GetOptions('h|help' => \$help,
    'r|regexp=s' => \@regexps,
    'd|dry-run' => \$dryrun,
    'v|verbose' => \$verbose
);

my @files = @ARGV;

if ($help || ! @files || ! @regexps) {
    print "Usage: rename.pl -r s/.../.../[g] [-r ...] [--dry-run] files\n";
    exit 1;
}

$verbose = 1 if $dryrun;

foreach $file (@files) {
    my $newfile = $file;

    foreach $regexp (@regexps) {
        $_ = $newfile;
        eval $regexp;
        $newfile = $_;

        if ($@) {
            die $@;
        }
    }

    print "$file => $newfile\n" if $verbose;
    $! = 0;
    rename $file, $newfile unless $dryrun;
    if ($!) {
        die $!;
    }
}


The command that fixed them all was this:

rename.pl -r 's/_/ /g' -r 's/\[(.*?)\] (.*?) \[(.*?)\]/$2 [$1] [$3]/' *

Wheeeee!

-- Des
Subscribe

  • (no subject)

    Well, I'm off to Dreamwidth. I hope to see you all there! Nice knowing you, LJ. It's been grand. — Des

  • A fresh start?

    So I'm thinking of moving away from LJ. Every time I glance at my ad blocker, there are an uncomfortably-large number of advertising and tracking…

  • 2012: Ramp It Up

    It’s that time of the year again -- another year has passed, and as usual, I don’t finish reflecting on it until the first 3 months of the following…

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 2 comments