perl - 使用 Perl 重命名目录中的文件

标签 perl file directory rename

我想要一个目录,对于所有电子邮件 (*.msg) 文件,删除开头的“RE”。我有以下代码,但重命名失败。

opendir(DIR, 'emails') or die "Cannot open directory";
@files = readdir(DIR);
closedir(DIR);

for (@files){
    next if $_ !~ m/^RE .+msg$/;
    $old = $_;
    s/RE //;
    rename($old, $_) or print "Error renaming: $old\n";
}

最佳答案

如果您的 ./emails目录包含以下文件:

1.msg
2.msg
3.msg

那么你的 @files看起来像 ('.', '..', '1.msg', '2.msg', '3.msg')但是你的 rename想要像 'emails/1.msg' 这样的名字, 'emails/2.msg'等。所以你可以 chdir 重命名前:
chdir('emails');
for (@files) {
    #...
}

您可能想查看 chdir返回值也是。

或者自己添加目录名称:
rename('emails/' . $old, 'emails/' . $_) or print "Error renaming $old: $!\n";
# or rename("emails/$old", "emails/$_") if you like string interpolation
# or you could use map if you like map

您可能希望使用 grep 将目录读取和过滤结合起来。 :
my @files = grep { /^RE .+msg$/ } readdir(DIR);

甚至这个:
opendir(DIR, 'emails') or die "Cannot open directory";
for (grep { /^RE .+msg$/ } readdir(DIR)) {
    (my $new = $_) =~ s/^RE //;
    rename("emails/$_", "emails/$new") or print "Error renaming $_ to $new: $!\n";
}
closedir(DIR);

关于perl - 使用 Perl 重命名目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8450812/

相关文章:

c++ - 在 C++ 中将复杂对象写入和读取到文件

php - 在文本文件中写入和读取 php 对象?

PHP - 在不同服务器上创建目录

perl - 在 Perl/Gtk 中显示 CP437 ('extended ascii' )

perl - 如何在perl中删除单引号但不删除撇号

perl - 如何将散列的一部分传递给子例程?

javascript - Selenium IDE - 显示意外警报!生成随机电子邮件 ID 时

javascript - 如何从已部署的 Meteor 应用程序的子目录中读取文件?

node.js - 从相对路径运行时,Nodejs 找不到包含内容

python - 使用 PFX 证书连接到 HTTP 站点