[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash script question

On Thu, Dec 07, 2006 at 12:16:54PM -0600, Nate Bargmann wrote:
> I have a directory of files that are created daily using 
> filename-`date +%Y%m%d`.tar.gz so I have a directory with files whose
> names advance from filename-20061201.tar.gz to filename-20061202.tar.gz
> to filename-20061203.tar.gz and so on.  Based on the date in the
> filename, I would like to delete any than are X days older than today's
> date.  So, I'm not interested in the actual created/modified date, just
> the numeric string in the name.

... what, no Perl one-liner yet?? :)

So, here it is, the line noise version that should do the job:

$ perl -MTime::Local -e 'unlink grep {/-(\d{4})(\d\d)(\d\d)/; timelocal(0,0,0,$3,$2-1,$1)<time-864000} glob "*.tar.gz"'

This would delete all of your .tar.gz files older than 10 days (or
864000 secs), in the current directory.


PS: Of course, you can add some whitespace and stuff, and make a script
out of this, e.g.


use Time::Local;

my $t_crit = time - 10*24*60*60;

    grep {
        timelocal(0,0,0,$3,$2-1,$1) < $t_crit;
        glob "*.tar.gz";

Or, even more verbose, almost self-documenting:

#!/usr/bin/perl -w

use Time::Local;

my $t_crit       = time - 10*24*60*60;
my $wildcard     = "*.tar.gz";
my $date_pattern = qr/-(\d{4})(\d\d)(\d\d)/;

my @files = glob $wildcard;

for my $file (@files) {
    my ($year, $mon, $day) = $file =~ $date_pattern;
    my $file_age = timelocal(0, 0, 0, $day, $mon-1, $year);
    unlink $file if $file_age < $t_crit;

Reply to: