Answers:
我认为@oHessling 几乎拥有它:不要解析ls,并且您可以在bash中做更多的事情:
four_days=$(date -d "4 days ago" +%Y%m%d)
for f in ABC_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].log; do
date=${f#ABC_}
date=${date%.log}
(( $date < $four_days )) && rm "$f"
done
four_days=$(echo "puts [clock format [clock scan {4 days ago}] -format %Y%m%d]" | tclsh)
一种使用方式perl
:
内容script.pl
:
use warnings;
use strict;
use Time::Local qw/timelocal/;
use File::Spec;
## Process all input files.
while ( my $file = shift @ARGV ) {
## Remove last '\n'.
chomp $file;
## Extract date from file name.
my ($date) = $file =~ m/.*_([^.]+)/ or next;
## Extract year, month and day from date.
my ($y,$m,$d) = $date =~ m/(\d{4})(\d{2})(\d{2})/ or next;
## Get date in seconds.
my $time = timelocal 0, 0, 0, $d, $m - 1, $y - 1900 or next;
## Get date in seconds five days ago.
my $time_5_days_ago = time - 5 * 24 * 3600;
## Substract them, and if it is older delete it and print the
## event.
if ( $time - $time_5_days_ago < 0 ) {
unlink File::Spec->rel2abs( $file ) and printf qq[%s\n], qq[File $file deleted];
}
}
为了测试它,我创建了一些文件:
touch ABC_20120430.log ABC_20120502.log ABC_20120320.log ABC_20120508.log ABC_20120509.log
用以下命令检查它们ls -1
:
ABC_20120320.log
ABC_20120430.log
ABC_20120502.log
ABC_20120508.log
ABC_20120509.log
script.pl
像这样运行脚本:
perl script.pl *.log
具有以下输出:
File ABC_20120320.log deleted
File ABC_20120430.log deleted
File ABC_20120502.log deleted
相反,您可以使用文件名将按时间顺序排序的事实。例如,要保留最后5个文件:
ls ABC_????????.log | head -n-5 | xargs rm
rm
除非您知道每次都在杀死小猫,否则请勿与xargs一起使用。如果您不知道为什么要进行一些研究并得知总是有更好的方法来解决可能是可以解决的任何问题,那将是一个坏主意。