0

我正在将数据提取到某个文本文件中,但首先我希望我的脚本检查文件是否存在,然后在某个文件夹中创建副本。如果它仍然存在于同一个文件夹中,请保存它,但附加值 _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 等...

我怎样才能做到这一点?

4

2 回答 2

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

不过请注意。如果您(或您和其他人)运行多个脚本实例,则可能会出现竞争条件。

于 2012-11-01T10:23:55.623 回答
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
于 2012-11-01T10:26:28.907 回答