Using Perl to rename files in a directory

前端 未结 4 410
故里飘歌
故里飘歌 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:03

    As already mentioned, your script fails because of the path you expect and the script uses are not the same.

    I would suggest a more transparent usage. Hardcoding a directory is not a good idea, IMO. As I learned one day when I made a script to alter some original files, with the hardcoded path, and a colleague of mine thought this would be a nice script to borrow to alter his copies. Ooops!

    Usage:

    perl script.pl "^RE " *.msg
    

    i.e. regex, then a file glob list, where the path is denoted in relation to the script, e.g. *.msg, emails/*.msg or even /home/pat/emails/*.msg /home/foo/*.msg. (multiple globs possible)

    Using the absolute paths will leave the user with no doubt as to which files he'll be affecting, and it will also make the script reusable.

    Code:

    use strict;
    use warnings;
    use v5.10;
    use File::Copy qw(move);
    
    my $rx = shift;   # e.g. "^RE "
    
    if ($ENV{OS} =~ /^Windows/) {  # Patch for Windows' lack of shell globbing
        @ARGV = map glob, @ARGV;
    }
    
    for (@ARGV) {
        if (/$rx/) {
            my $new = s/$rx//r;  # Using non-destructive substitution
            say "Moving $_ to $new ...";
            move($_, $new) or die $!;
        }
    }
    

提交回复
热议问题