0

我正在尝试重命名文件夹中的所有 tif 文件并将它们从 1 编号为 x。前任。初始文件名“image-2.tif”和“image-3.tif”将重命名为“file1.tif”和“file2.tif”。

这是我的代码:

my $dirname = "../folder";
opendir (DIR, $dirname) or die "cannot open directory $dirname";
my @files = grep /.tif/, readdir DIR;
closedir (DIR);

my $basename = "file";
my $count = 1;
my $new;
foreach (@files) {
$new = "${basename}${count}.tif";
print "rename $_ ${basename}${count}.tif\n";
rename $_, $new;
$count++;
}

尽管所有文件都被正确读取,但它们只是没有被重命名。

4

3 回答 3

3

当您从另一个文件中获取文件时,您需要为您的rename()函数使用一个好的路径。该模块File::Spec可以帮助获得它:

use File::Spec;

my $dirname = "../folder";
my $abs_path = File::Spec->rel2abs($dirname);

和:

foreach (@files) {
    $new = "${basename}${count}.tif";
    print "rename $_ ${basename}${count}.tif\n";
    rename File::Spec->catfile($abs_path, $_), File::Spec->catfile($abs_path, $new);
    $count++;
}
于 2013-11-04T17:57:16.863 回答
2

我建议改变你的路线:

rename $_, $new;

...更像是:

rename($_, $new) or warn "rename: $_: $new: $!\n";

...并且您应该能够看到它为什么不起作用-因为失败会rename返回false(并$!会告诉您失败的原因)。

此外,您的rename操作目标(在您的情况下$new:)也需要包含目录组件(否则,您试图将文件移动到进程的当前工作目录(可能不是您想要的))。

最后,我建议不要将 的值硬编码为$dirname相对路径,而应将其作为命令行参数接受。这允许您的脚本从任何$PWD. 请参阅手册页和/或内置@ARGV命令。perlvarshift

因此,像这样:

my $dirname = shift; # Accept dirname as commandline argument
opendir (DIR, $dirname) or die "cannot open directory $dirname";
my @files = grep /\.tif$/, readdir DIR; # Escape regex meta-char (.) and anchor to end of string ($).
closedir (DIR);

my $basename = "file";
my $count = 1;
my $new;
foreach (@files) {
    $new = "${dirname}/${basename}${count}.tif"; # Include dirname in target path
    print "rename $_ $new\n";
    rename($_, $new) or warn "rename: $_: $new: $!\n"; #warn when rename fails
    $count++;
}
于 2013-11-04T19:06:43.017 回答
0

我终于找到了我想要的东西。在 Tim Peoples 的回应的帮助下。最简单的回应是:

my $dirname = "../folder";
opendir (DIR, $dirname) or die "cannot open directory $dirname";
my @files = grep /[.]tif\z/, readdir DIR; #corrected pattern based on Sinan Ünür's comment
closedir (DIR);

my $basename = "file";
my $count = 1;
my $new;
foreach (@files) {
$new = "${basename}${count}.tif";
print "rename $_ $new\n";
rename ("$dirname/$_", "$dirname/$new") or warn "rename: $_: $new: $!\n"; #directory name     added to both the original file name and new file name. Thanks to Tim for helping me found this error using warn.
$count++;
}
于 2013-11-04T19:47:09.477 回答