วิธีหนึ่งในการใช้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