Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

shell - 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:

  1. It is not detecting .txt files, otherwise .data,.exe,.dat etc it is detecting.
  2. Also -mtime is 365. But a leap year(366 days) I have to change my script.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$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
");
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
";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...