Perl - 创建文件的编号备份副本

时间:2012-11-01 10:16:16

标签: perl file-exists file-copying

我正在将数据提取到某个文本文件,但首先我希望我的脚本检查文件是否存在,然后在某个文件夹中创建副本。如果它仍然存在于同一个文件夹中,请保存它,但附加类似值_1或_2 ...取决于最后一个文件的值。

这是我目前的脚本,

if (-e "/tmp/POP_Airtime_Week1.txt"){

    copy("/tmp/POP_Airtime_Week1.txt","/tmp/POP") || die "cannot copy file";
    # If the file exists create a copy in /tmp/POP

    #################################
    # IF FILE EXISTS IN /tmp/POP copy the file but rename it to 
    # POP_Airtime_Week1_1.txt then increase the numbers each time
    # the script is run and a new copy needs to be created.
    ##################################

    unlink ("/tmp/POP_Airtime_Week1.txt");

}

如果/tmp/POP/POP_Airtime_Week1.txt存在,则复制它,但将其另存为/tmp/POP/POP_Airtime_Week1_1.txt。下次运行脚本并且/tmp/POP/POP_Airtime_Week1.txt存在时,请将其复制并保存为/tmp/POP/POP_Airtime_Week1_2.txt等等。

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以在目标文件存在时递增变量:

my $name = "POP_Airtime_Week1";
if (-e "/tmp/POP/$name.txt") {
    my $num = 1;
    $num ++ while (-e "/tmp/POP/$name\_$num.txt");
    copy("/tmp/$name.txt","/tmp/POP/$name\_$num.txt") or die "cannot copy file";
} else {
    copy("/tmp/$name.txt","/tmp/POP/$name.txt") or die "cannot copy file";
}
但是,请注意。如果您(或您和其他人)运行多个脚本实例,则可能存在竞争条件。

答案 1 :(得分:0)

 my $i = 0;
 my $fname = $file;
 for (;;) {
     last unless -f $fname;
     $i++;
     $fname = "${file}_$i";
 }
 # $fname is new unused file name, copy to it