Clean files

#!/usr/bin/perl

################################################################
#                                                              #
#  Program:  clean_dir.pl                                      #
#                                                              #
#  Description:  to allow a .sh script to delete old files     #
#                                                              #
#  Usage:  clean_dir.pl          #
#  Example:  clean_dir.pl .log 5d                              #
#                                                              #
#  Returns:  nothing                                           #
#                                                              #
#                                                              #
#                                                              #
#                                                              #
################################################################

$DEBUG = 0;

if ($#ARGV < 2) {
   die" Usage:  clean_dir.pl \n";
}

($dir,$match_str,$age_str) = @ARGV;

if ($DEBUG) {
  print "Original Pattern Match = $match_str\n";
}

if ($match_str) {
   $match_str =~ s/\./\\./go;
   $match_str =~ s/\*/\.\*/go;
} else {
   $match_str = ".*";
}

if ($DEBUG) {
  print "Pattern Match = $match_str\n";
}

$age_num = &get_age($age_str);


@file_list = &get_files($dir,$match_str,$age_num);
my($counter) = 0;
foreach (@file_list) {
   $file_age = (-M "$dir/$_");
   unlink("$dir/$_")&&$counter++;
   if ($DEBUG) {
      print "$dir/$_ removed\n";
   }
}
print $counter." files removed\n";


sub get_files {
   my($dir,$match,$age) = ($_[0],$_[1],$_[2]);
    opendir(DIR, $dir) || die "can't opendir $dir: $!";
    @flist = grep { /^$match$/ && -f "$dir/$_" && ( -M "$dir/$_" > $age ) } readdir(DIR);
    closedir DIR;
    return @flist;

}
sub get_age {
   my($age_str) = $_[0];
   my($mult) = 1.0;
   $age_str =~ m#^(\d+)(\w*)$#;
   my($age_num,$duration) = ($1,$2);

   if ($duration =~ /h/) {
      $mult = (1/24);
   } elsif ($duration =~ /w/) {
      $mult = (7);
   } else {
# if no time notation, assumed to be in days already
   }

   $age_num *= $mult;

}


Use example:

backupsum=`find /home/db2inst1/BACKUP -name "CVICTL*" -print |wc -l`
if [ $backupsum -gt 1 ]
then
/home/db2inst1/clean_dir.pl /home/db2inst1/BACKUP "CVICTL*" 21d
fi
请使用浏览器的分享功能分享到微信等