Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Renaming Files with Regular Expressions

by svsingh (Priest)
on Dec 02, 2003 at 18:25 UTC ( #311703=CUFP: print w/ replies, xml ) Need Help??

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

Comment on Renaming Files with Regular Expressions
Select or Download Code
Re: Renaming Files with Regular Expressions
by cchampion (Curate) on Dec 02, 2003 at 18:50 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://311703]
Approved by Paladin
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2014-08-01 06:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (257 votes), past polls