in reply to removing files with perl based on age and name
You can skip the "warn" outputs if you like, but for this sort of thing, I think it's nice to keep a log of what actually happens on a given run.#!/usr/bin/perl use strict; use warnings; die "Usage: $0 directory_path\n" unless ( @ARGV == 1 and -d $ARGV[0] ) +; my $target_dir = shift; chdir $target_dir or die "chdir $target_dir: $!\n"; opendir( my $dir, "." ); my %files = map { $_ => -M } grep /\w/, readdir( $dir ); my @bacs = sort { $files{$a} <=> $files{$b} } grep /\.bac$/, keys %fil +es; @bacs or die "No *.bac file found in $target_dir - nothing to do\n"; my $latest_bac_age = $files{$bacs[0]}; ( my $latest_bac_id = $bacs[0] ) =~ s/^(\w+).*/$1/; warn "latest bac file in $target_dir is $bacs[0]\n"; for my $f ( keys %files ) { my $result = "kept"; if ( $files{$f} > $latest_bac_age and $f !~ /^$latest_bac_id/ and +-f $f ) { unlink $f and $result = "deleted"; } warn "$result $f\n"; }
Updated the script to include the two "… or die …" conditions -- I should have had those in there from the beginning. Also updated the logic in the for loop: added the "-f $f" condition to the "if" statement (no point trying to unlink sub-directories), and only report "deleted" if the deletion actually succeeds.
|
|---|