简体   繁体   中英

Perl - Rename and Sort Image Files

I have some images I want to Rename and sort, but when I rename them they aren't renaming in the same order. I'm getting the output I want but they are not sorted from the original. Really what I'm asking is how to match and substitute the example below.

Code is current output:
image_1_0.jpg -> 6.jpg
image_1_1.jpg -> 4.jpg

Code output wanted:
image_1_0.jpg -> 1.jpg
image_1_1.jpg -> 2.jpg

images folder


image_1_0.jpg
image_1_1.jpg
image_2_0.jpg
image_2_1.jpg
image_3_1.jpg
image_3_2.jpg
image_3_3.jpg
image_4_0.jpg
image_5_0.jpg

output would be

1.jpg
2.jpg
3.jpg
4.jpg
5.jpg
6.jpg
7.jpg
8.jpg
9.jpg

Here's what I have

#! /usr/bin/perl
use warnings;
use strict;

my $file;
my @imagesFile;
my $counter = 0;

my $dir = 'usr/local/bin/images';

opendir (IMGDIR, "$dir") or die "Cannot open directory: $!";
@imagesFile = (readdir(IMGDIR));
closedir IMGDIR;

foreach my $file(@imagesFile){
$counter++;

rename "$dir/$file", "$dir/$counter.jpg";

}

Could use some insight on this issue.

The readdir isn't going to return the filenames in sorted order. If you want the images to be in some order as you increment their final names, you have to do that yourself.

my @files = sort readdir($dh);

And, you probably want to at least remove the . and .. virtual directories, as well as any other files you don't want to target. Even better is selecting the files that you do want:

my @files = sort grep /image_\d_\d.jpg/, readdir($dh);

Please inspect following code for compliance with your requirements.

#!/usr/bin/env perl
#
# vim: ai ts=4 sw=4

use strict;
use warnings;

my $counter = 0;

rename $_, ++$counter . '.jpg' for sort glob("*.jpg");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM