Created
December 21, 2011 20:20
-
-
Save johnhaitas/1507529 to your computer and use it in GitHub Desktop.
Perl - delete files in folder older than ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use File::Find; | |
my $backup_root = "/path/to/folder" | |
# purge backups older than AGE in days | |
my @file_list; | |
my @find_dirs = ($backup_root); # directories to search | |
my $now = time(); # get current time | |
my $days = 30; # how many days old | |
my $seconds_per_day = 60*60*24; # seconds in a day | |
my $AGE = $days*$seconds_per_day; # age in seconds | |
find ( sub { | |
my $file = $File::Find::name; | |
if ( -f $file ) { | |
push (@file_list, $file); | |
} | |
}, @find_dirs); | |
for my $file (@file_list) { | |
my @stats = stat($file); | |
if ($now-$stats[9] > $AGE) { | |
unlink $file; | |
} | |
} | |
print "Deleted files older than $days days.\n"; |
There is a syntax error at line 7
I should be --> my $backup_root = "/path/to/folder";
; is missing
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this example! I found it handy for a cronjob task. I added the ability to delete files in a symlink directory:
#!/usr/bin/perl
use File::Find;
my $backup_root = "/path/to/folder"
#purge backups older than AGE in days
my @file_list;
my @find_dirs = ($backup_root); # directories to search
my $now = time(); # get current time
my $days = 30; # how many days old
my $seconds_per_day = 606024; # seconds in a day
my $AGE = $days*$seconds_per_day; # age in seconds
sub wanted {
my $file = $File::Find::name;
if ( -f $file ) {
push (@file_list, $file);
}
}
#Execute wanted sub routine for every file in find_dirs, follow symlinks
find ({ wanted => &wanted, follow => 1}, @find_dirs);
for my $file (@file_list) {
my @stats = stat($file);
#stat[9] is mtime - last modify time
if ($now-$stats[9] > $AGE) {
unlink $file;
}
}
printf("Deleted files older than $days days.\n");