Perl - 重命名目录中的图像文件
Perl - Rename image files in directory
我不经常使用 perl。我有一个图像文件列表,需要使用递增计数器重命名。
images folder
image_1_0.jpg
image_1_1.jpg
image_2_0.jpg
image_2_1.jpg
image_3_0.jpg
image_3_1.jpg
image_3_2.jpg
image_4_0.jpg
image_5_0.jpg
image_5_1.jpg
image_5_2.jpg
image_5_3.jpg
image_5_4.jpg
image_5_5.jpg
output would be
1.jpg
2.jpg
3.jpg
4.jpg
5.jpg
6.jpg
7.jpg
8.jpg
9.jpg
10.jpg
11.jpg
12.jpg
13.jpg
14.jpg
15.jpg
我目前拥有的
my $dir = usr/local/bin/images
my counter = 0;
opendir (IMGDIR, "$dir") or die "Cannot open directory: $!";
my @files = readdir(IMGDIR);
foreach my $oldfile(@files){
(my $oldfileb = $oldfile =~ s/\.[^.]+$//; #get file without extention
my $newfile = $dir/"$counter".jpg;
rename ("$dir/$oldfileb", "dir/$newfile");counter++;
}
尝试更多地使用 Perl,但需要一些帮助。错误是在代码的反部分
使用
启动脚本
#! /usr/bin/perl
use warnings;
use strict;
参见 strict and warnings。 Perl 将保护您免受最常见的错误。
字符串必须用引号括起来,如果后面有另一个语句,则每个语句都应以分号结尾:
my $dir = 'usr/local/bin/images';
变量必须以印记开头:
my $counter = 0;
括号必须闭合:
(my $oldfileb = $oldfile) =~ s/\.[^.]+$//;
从 Perl 5.14 开始,您还可以使用更具可读性的 /r
修饰符:
my $oldfileb = $oldfile =~ s/\.[^.]+$//r;
请注意,您应该跳过看起来不像图像名称的文件(readdir will return .
and ..
on *nix, for example). You also might want to sort 文件。
/
引号外是除法,.
是串联。
my $newfile = "$dir/$counter.jpg";
您已将 $dir
包含在 $newfile
中:
rename "$dir/$oldfileb", $newfile;
检查 rename 的 return 值是否有错误。
rename "$dir/$oldfileb", $newfile or warn "Can't rename $oldfile: $!";
我不经常使用 perl。我有一个图像文件列表,需要使用递增计数器重命名。
images folder
image_1_0.jpg
image_1_1.jpg
image_2_0.jpg
image_2_1.jpg
image_3_0.jpg
image_3_1.jpg
image_3_2.jpg
image_4_0.jpg
image_5_0.jpg
image_5_1.jpg
image_5_2.jpg
image_5_3.jpg
image_5_4.jpg
image_5_5.jpg
output would be
1.jpg
2.jpg
3.jpg
4.jpg
5.jpg
6.jpg
7.jpg
8.jpg
9.jpg
10.jpg
11.jpg
12.jpg
13.jpg
14.jpg
15.jpg
我目前拥有的
my $dir = usr/local/bin/images
my counter = 0;
opendir (IMGDIR, "$dir") or die "Cannot open directory: $!";
my @files = readdir(IMGDIR);
foreach my $oldfile(@files){
(my $oldfileb = $oldfile =~ s/\.[^.]+$//; #get file without extention
my $newfile = $dir/"$counter".jpg;
rename ("$dir/$oldfileb", "dir/$newfile");counter++;
}
尝试更多地使用 Perl,但需要一些帮助。错误是在代码的反部分
使用
启动脚本#! /usr/bin/perl
use warnings;
use strict;
参见 strict and warnings。 Perl 将保护您免受最常见的错误。
字符串必须用引号括起来,如果后面有另一个语句,则每个语句都应以分号结尾:
my $dir = 'usr/local/bin/images';
变量必须以印记开头:
my $counter = 0;
括号必须闭合:
(my $oldfileb = $oldfile) =~ s/\.[^.]+$//;
从 Perl 5.14 开始,您还可以使用更具可读性的 /r
修饰符:
my $oldfileb = $oldfile =~ s/\.[^.]+$//r;
请注意,您应该跳过看起来不像图像名称的文件(readdir will return .
and ..
on *nix, for example). You also might want to sort 文件。
/
引号外是除法,.
是串联。
my $newfile = "$dir/$counter.jpg";
您已将 $dir
包含在 $newfile
中:
rename "$dir/$oldfileb", $newfile;
检查 rename 的 return 值是否有错误。
rename "$dir/$oldfileb", $newfile or warn "Can't rename $oldfile: $!";