?

Log in

Nifty Perlage - The Desian Universe
Links Home / GitHub January 2017
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
 
 
 
deskitty
deskitty
Des
Sat, Aug. 20th, 2005 11:13 pm
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

Current Mood: geeky geeky

2CommentReplyShare

moment_of_me
moment_of_me
moment_of_me
Sun, Aug. 21st, 2005 01:26 pm (UTC)

Mmmmmmmmm. Babe. Some should arrest you for indecent geekage. You can't walk around waving it around without a license. ::purrs and licks you::


ReplyThread
deskitty
deskitty
Des
Sun, Aug. 21st, 2005 05:40 pm (UTC)

Heeee. >:D

I need a license, do I? Does this mean I need to wear it on a collar so it's properly displayed?


ReplyThread Parent