使用Perl重命名目录中的文件 [英] Using Perl to rename files in a directory

查看:111
本文介绍了使用Perl重命名目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拿一个目录和所有的电子邮件(* .msg)文件,一开始就删除'RE'。我有以下代码,但重命名失败。

I'd like to take a directory and for all email (*.msg) files, remove the 'RE ' at the beginning. I have the following code but the rename fails.

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";
}


推荐答案

如果您的 ./电子邮件目录包含这些文件:

If your ./emails directory contains these files:

1.msg
2.msg
3.msg

然后你的 @files 将看起来像('。','..','1.msg','2.msg','3.msg')您的重命名需要名称,如'emails / 1.msg''电子邮件/ 2。 msg'等等。所以你可以 chdir ,然后重命名:

then your @files will look something like ('.', '..', '1.msg', '2.msg', '3.msg') but your rename wants names like 'emails/1.msg', 'emails/2.msg', etc. So you can chdir before renaming:

chdir('emails');
for (@files) {
    #...
}

您可能还想查看 chdir 返回值。

You'd probably want to check the chdir return value too.

或者自己添加目录名称:

Or add the directory names yourself:

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

You might want to combine your directory reading and filtering using 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重命名目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆