Perl Script to remove files older than a year

2019-06-11 14:27发布

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.

标签: perl shell
3条回答
走好不送
2楼-- · 2019-06-11 14:50
$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";
查看更多
▲ chillily
3楼-- · 2019-06-11 14:53

You can also use the command find2perl. Like:

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

What will produce a perl script to use the File::Find - e.g.:

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");
}
查看更多
神经病院院长
4楼-- · 2019-06-11 15:04

Use the brilliant Path::Class to make life easy:

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->();
} );
查看更多
登录 后发表回答