旋转文件

Mou*_*Dog 2 rename files

我有一个写入文件的应用程序。在运行应用程序之前,我想旋转文件。

换句话说; 重命名现有文件,使其file.n变为file.n+1, (并重file.1命名为file.2),而不会覆盖现有文件。

我可以写一个脚本来做到这一点,但我想知道是否有更简单的方法?

gol*_*cks 5

我可以写一个脚本来做到这一点

如果你想节省一些时间,这里是 perl 版本:

#!/usr/bin/perl
use strict;
use warnings FATAL => qw(all);

# Rotate files (file -> file.1, file.1 -> file.2, etc).

if ($#ARGV < 0 || !-e -w $ARGV[0] || index($ARGV[0], '/') != -1) {
        print "Existing file basename required\n";
        exit 1;
}

my $name = $ARGV[0];

opendir my $dh, './';
my @files = ();
my $last = 0;
while (readdir $dh) {
        next if !($_ =~ m/^$name\.(\d+)$/);
        $last = $1 if $1 > $last;
}
close $dh;

for (my $i = $last; $i > 0; $i--) {
        rename "$name.$i", "$name.".($i + 1);
}

rename $name, "$name.1";
Run Code Online (Sandbox Code Playgroud)

您只能在当前工作目录中的文件上使用它。例如:

rotate whatever.file
Run Code Online (Sandbox Code Playgroud)

如果附加了任何类型的路径,它将引发错误。然而,修改以允许路径并不难。

此外,如果有一个whatever.file.0它将被忽略(它产生的文件从 1 开始编号)。