以尽可能简单的方式,我想知道是否有人知道如何通过简单地将当前的“localtime()”命名为文件名的一部分来将 .log 文件归档到 Windows XP 目录中?(不要假设日志文件被锁定。)我尝试了各种不同的方法,但无法解决它......而且网络上没有好的例子。
这是我正在寻找的:
for (all files > that 1 day old)
rename file to file.[datestamp].log
end
好吧,这看起来很容易,我可能误解了一些东西。任务是将例如“yada.log”移动到“yada.2011-05-04.log”?那么这个怎么样:
use strict;
use warnings;
use File::Copy;
use POSIX qw(strftime);
my $dir = $ARGV[0] or die "Usage: $0 <directory>";
my $now_string = strftime "%Y-%m-%d_%H%M%S", localtime;
opendir DIR, $dir or die $!;
my @files = readdir DIR;
chdir $dir or die $!;
for my $file (@files) {
next if (-d $file);
next unless ($file =~ /^(.*)(\.log)$/i);
my $dst = $1 . "." . $now_string . $2;
move ($file, $dst) or die "Failed to move $file: $!";
}
opendir(FILES, '*logdir*');
my @files = readdir FILES;
closedir(FILES);
foreach(@files){
system "move $_ $_.".localtime().".log" if -A $_ > *age*;
}
多亏了 TLP,这就是我最终做到的方式!这个脚本在第 12 行有问题,但几乎没有用。
use strict;
use warnings;
use File::Copy;
use POSIX qw(strftime);
my $dir;
my $file;
if ( @ARGV = 2 ) {
print "Two args accepted.";
$dir = $ARGV[0] or die "Usage: <directory> <filename>";
$file = $ARGV[1] or die "Usage: <directory> <filename>";
goto runblock;
}
else { print "Number of arguments must be 2: directory filename\n"; goto fail; }
runblock: print "Renaming $file .\n";
chdir $dir or die $!;
my $now_string = strftime "%Y-%m-%d_%H%M%S", localtime;
if (-e $file) {
if (-A $file > 7 ) {
my $dst = "siteAlive." . $now_string . ".log";
move($file, $dst) or die "Failed to move $file: $!";
goto endscript;
}
}
fail: print "Failed to rename $file . Try again.\n" ;
endscript: print "End of script.\n";
也许有一些模块可以为您做到这一点,Logfile::Rotate
例如。