I was cleaning up my mp3 collection and realized I needed to do some file renaming. Some of it was easy, and some of it was a bit more complicated. I tried the
Cookbook Example, but it didn't have a preview option (something I needed because I often get regexes wrong on the first try).
It's useful for me, hopefully someone else will find it handy as well.
Note: This was tested on Windows. I haven't run it on a Unix platform yet.
use strict;
&renameFiles( &getArgs() );
# ------------------- SUBROUTINES -------------------
sub printUsage {
print <<EOF;
Usage:
> perl renrx.pl ["<regex>" [<preview>]]
Where,
* <regex> the regular expression to use
* <preview> is 0 to disable preview; anything otherwise
EOF
}
sub getArgs {
my ($reg, $prompt) = ("", 1);
if ( @ARGV == 2 ) {
($reg, $prompt) = @ARGV;
unless ( $prompt == 0 ) { $prompt = 1; }
} elsif ( @ARGV == 1 ) {
($reg) = @ARGV;
} else {
# unexpected number of args
&printUsage();
exit;
}
return ($reg, $prompt);
}
sub renameFiles {
my ($reg, $prompt) = @_;
my @files = <*>;
foreach (@files) {
my $before = $_;
eval $reg;
my $after = $_;
if ( $before eq $after ) { next; } # nothing to do
if ( $prompt ) {
print "$before => $after\n";
print "Rename? [Yes|No|Always|Cancel] ";
chomp (my $resp = <STDIN>);
if ( $resp =~ m/^y/i ) {
# do nothing
} elsif ( $resp =~ m/^n/i ) {
next;
} elsif ( $resp =~ m/^a/i ) {
$prompt = 0;
} elsif ( $resp =~ m/^c/i ) {
exit;
} else {
print "Invalid choice.\n";
exit;
}
} # if prompt
rename( $before, $after );
}
}
As an example, the following swaps the artist name and song titles for me:
Command:
perl renrx "s|(.*?)(\d\d) ([^_]+) _ (.*?)(\.mp3)|$1$2 $4 _ $3$5|"
Output:
Maybe-01 Winter Wonderland _ Phantom Planet.mp3 => Maybe-01 Phantom Pl
+anet _ Winter Wonderland.mp3
Rename? [Yes|No|Always|Cancel] y
Maybe-02 Maybe this Christmas _ Ron Sexsmith.mp3 => Maybe-02 Ron Sexsm
+ith _ Maybe this Christmas.mp3
Rename? [Yes|No|Always|Cancel] a
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.