[英]Perl Script to remove files older than a year
I am trying to make a script which will delete files older than a year. 我正在尝试制作一个脚本,该脚本将删除早于一年的文件。
This is my code: 这是我的代码:
#!/usr/bin/perl
$files = ".dat|.exe";
@file_del = split('\|',$files);
print "@file_del";
$dates = "365|365|365|365";
@date_del = split('\|',$dates);
if($#date_del == 0){
for $i (@file_del){
my $f = `find \"/Users/ABC/Desktop/mydata\" -name *$i -mtime +date[0]`;
print "$f";
}
}
else{
for $i (0..$#file_del){
my $f = `find \"/Users/ABC/Desktop/mydata\" -name *$file_del[$i] -mtime +$date_del[$i]`;
print "$f";
}
}
Issues I am facing: 我面临的问题:
$myDir = "/Users/ABC/Desktop/mydata/";
$cleanupDays = 365
$currentMonth = (localtime)[4] + 1;
$currentyear = (localtime)[5] + 1900;
if ($currentMonth < 3) {
$currentyear -= 1;
}
if( 0 == $currentyear % 4 and 0 != $currentyear % 100 or 0 == $currentyear % 400 ) {
$cleanupDays += 1;
}
$nbFiles = 0;
$runDay = (time - $^T)/86400; # Number of days script is running
opendir FH_DIR, $myDir
or die "$0 - ERROR directory '$myDir' doesn't exist\n");
foreach $fileName (grep !/^\./, (readdir FH_DIR)) {
if (((-M "$myDir$fileName") + $runDay) > $cleanupDays) {
unlink "$myDir$fileName" or print "ERROR:NOT deleted:$fileName ";
$nbFiles++;
}
}
closedir FH_DIR;
print "$nbFiles files deleted\n";
Use the brilliant Path::Class to make life easy: 使用出色的Path :: Class使生活变得轻松:
use Modern::Perl;
use Path::Class;
my $dir = dir( '/Users', 'ABC', 'Desktop', 'mydata' );
$dir->traverse( sub {
my ( $child, $cont ) = @_;
if ( not $child->is_dir and $child->stat ) {
if ( $child->stat->ctime < ( time - 365 * 86400 ) ) {
say "$child: " .localtime( $child->stat->ctime );
# to delete:
# unlink $child;
}
}
return $cont->();
} );
You can also use the command find2perl
. 您也可以使用命令
find2perl
。 Like: 喜欢:
find2perl . -mtime -365 -exec rm {} \;
What will produce a perl script to use the File::Find
- eg: 什么会产生一个Perl脚本来使用
File::Find
例如:
use strict;
use File::Find ();
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;
sub wanted;
File::Find::find({wanted => \&wanted}, '.');
exit;
sub wanted {
my ($dev,$ino,$mode,$nlink,$uid,$gid);
(($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
(int(-M _) < 365) &&
(unlink($_) || warn "$name: $!\n");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.