Skip to content

Instantly share code, notes, and snippets.

@johnhaitas
Created December 21, 2011 20:20
Show Gist options
  • Save johnhaitas/1507529 to your computer and use it in GitHub Desktop.
Save johnhaitas/1507529 to your computer and use it in GitHub Desktop.
Perl - delete files in folder older than ...
#!/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";
@iDemonix
Copy link

Wouldn't it be more efficient to simply do:

my $AGE = $days * 86400;

@rachmari
Copy link

rachmari commented Apr 12, 2017

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

@SubhoGiri
Copy link

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