Renaming picture in folders...
A200560
created: 2006-01-04 08:55:01
I have a set of folders with some images in each. Imaging this:
/Folder_1
/Folder_2
/Folder_3
/Folder_4
.. . . Now, each of those directories has images called with names like "475849.jpg" I want to get everyone of those "475849.jpg" recursively and rename their with names like Folder_x_y where the y is a progressive number and "Folder_x" is the name of the folder which contains them. How can I accomplish this with a fast Linux Perl script? Thanks for the help.
Re: Renaming picture in folders...
created: 2006-01-04 08:57:42

Start with File::Find

Re: Renaming picture in folders...
created: 2006-01-04 09:48:37

[cpan://File::Wildcard] is designed for this kind of job. Warning: untested

use File::Wildcard;

my $wc = File::Wildcard->new(
        path => './//',
        match => qr{^(.*?Folder_\d+)/(\w+.jpg)$},
        derive => [ '$1_$2' ],
        );
while (my $match = $wc->next) {
        my ($from,$to) = @$match;
        print "Renaming $from to $to\n";
        rename $from $to;
}

--

Oh Lord, won’t you burn me a Knoppix CD ?
My friends all rate Windows, I must disagree.
Your powers of persuasion will set them all free,
So oh Lord, won’t you burn me a Knoppix CD ?
(Missquoting Janis Joplin)

Re: Renaming picture in folders...
created: 2006-01-04 09:57:39
You don't say whether the progressive number is per folder or for the whole run - I've gone for per-folder here - if you want for the whole run then change the hash $num{$dir} to a scalar $num instead.
#!/usr/bin/perl

use strict;
use warnings;

use File::Find;
use File::Copy;

#
# Set this to 0 to turn off printing which files it's moving.
#
my $verbose = 1;

my @dirs = qw(
    Folder_1
    Folder_2
    Folder_3
    Folder_4
);

my %num;

sub wanted {

    if ( -f $_ ) {

        my $dir = $File::Find::dir;

        $num{$dir}++;

        my $src = "$dir/$_";
        my $target = "${dir}_$num{$dir}.jpg";
        my $mv_msg = "move '$src' to '$dir/$target'";

        if ( -f $target ) {

            die "Can't $mv_msg: File already exists!\n"

        }
        else {

            move( $_, $target ) || die "Can't $mv_msg: $!\n";

            print "$mv_msg OK\n" if ($verbose);

        }

    }

}

File::Find::find( { wanted => \&wanted }, @dirs );
I'm also presuming here that you want them left in the same directory they were in - not moved up.
Re^2: Renaming picture in folders...
created: 2006-01-04 12:41:19
Thanks serf, very useful, I optimized (for SEO purposes) an images gallery of about 4000 images. Thanks and Happy New Year!
Re: Renaming picture in folders...
created: 2006-01-04 13:39:12
could be this?
perl -e 'while(<./*>){$folder=$_;$y=0;while(<$_/*.jpg>){rename $_, $folder."/".$folder."_".$y++.".jpg"}}'

perlmonks.org content © perlmonks.org and A200560, dorward, rinceWind, serf, smokemachine

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03