Using Perl to rename files in a directory

前端 未结 4 421
故里飘歌
故里飘歌 2021-01-12 10:56

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(D         


        
4条回答
  •  半阙折子戏
    2021-01-12 11:30

    If your ./emails directory contains these files:

    1.msg
    2.msg
    3.msg
    

    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) {
        #...
    }
    

    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
    

    You might want to combine your directory reading and filtering using grep:

    my @files = grep { /^RE .+msg$/ } readdir(DIR);
    

    or even this:

    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);
    

提交回复
热议问题