http://www.perlmonks.org?node_id=311703

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