Perl脚本删除超过一年的文件

时间:2014-07-17 18:08:50

标签: perl shell

我正在尝试创建一个删除超过一年的文件的脚本。

这是我的代码:

#!/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";
    }
   }

我面临的问题:

  1. 它没有检测到.txt文件,否则检测到.data,.exe,.dat等。
  2. 同样-mtime是365.但是闰年(366天)我必须改变我的剧本。

3 个答案:

答案 0 :(得分:1)

$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";

答案 1 :(得分:0)

使用辉煌的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->();
} );

答案 2 :(得分:0)

您也可以使用命令find2perl。像:

find2perl . -mtime -365 -exec rm {} \;

什么会生成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");
}