Bastille has asked for the wisdom of the Perl Monks concerning the following question:

Greetings, this is my first time messing around with perl so I'm rather in the dark regarding how to proceed with this.

I have around 100k image files that I want to change the naming structure for. They all follow the structure of "some amount of words 1 - 001.jpg" to "some amount of words 100 - 001.jpg" and I want to make it so the first set of numbers are all padded to three digits long like the second set.

The files are all within sub-folders of one main folder and my OS is Windows 7. Thanks in advance for anything willing to shed some light on how to go about this task.

Replies are listed 'Best First'.
Re: Mass file renaming help
by BrowserUk (Patriarch) on Aug 01, 2010 at 21:27 UTC

    Wrapped for posting. Remove the say and qq[] once you're sure it would do the right thing:

    perl -E"$o=$_ and s[^(.+)(\d+)( - \d+\.jpg)][$1.sprintf('%03d',$2).$3]e and say qq[rename $o $_] for map{ glob $_ .'\*.jpg'} grep{ -d } glob $ARGV[0]" \theDir\*
Re: Mass file renaming help
by Utilitarian (Vicar) on Aug 01, 2010 at 21:27 UTC
    • use File::Find to get an array of the file names.
    • Then you can use a regex to separate the file names into their constituent parts. eg
      my($words,$fix_num,$remainder)= $filename=~ /(.*?)(\s\d+)(\s-\s\d{3}\.jpg)/;
    • sprintf will then allow you to specify the padding on $fix_num
    • Then rename the files with rename
    Have a go at doing this and come back with your code if you have any problems ;)

    print "Good ",qw(night morning afternoon evening)[(localtime)[2]/6]," fellow monks."
Re: Mass file renaming help
by repellent (Priest) on Aug 02, 2010 at 00:43 UTC
    Download rename as rename.pl. On the command line, type:
    perl rename.pl -n "s{(\d+)(?= - \d+\.jpg$)}{ sprintf q(%03d), $1 }e" * +.jpg

    Remove -n switch to actually do the renaming.

    Note: Command provided is quoted for cmd.exe.

    Update: Added more details.