Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Deleting files

by mallen (Acolyte)
on Feb 02, 2004 at 15:33 UTC ( [id://325877]=perlquestion: print w/replies, xml ) Need Help??

mallen has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to delete some files from a dir on win 2000. I am using the unlink, but what I really want is to delete everything that is older than five days from the days date. Can anyone lead me in the right direction on how to do this. I am somewhat new to perl. Thanks, Mark

Replies are listed 'Best First'.
Re: Deleting files
by blue_cowdawg (Monsignor) on Feb 02, 2004 at 15:50 UTC

    Check out the find2perl command. I believe you would be looking for:

    find2perl SOMEDIR -mtime +5 -print
    If you re-direct the results to a file you will end up with a skeleton of a perl script you can modify. Change the pertinate lines to make it do what you want. Further, you want to look at Perl's unlink command which does file removal.

    Another way of doing it:

    # hand waving prior to this # chdir $MYDIR; opendir(DIR,"$MYDIR") or die "Could not open $MYDIR:$!"; while (my $file=readdir(DIR)){ my $age= -M $file; unlink $file if int($age) > 5; } closedir(DIR);
    YMMV, HTH


    Peter L. Berghold -- Unix Professional
    Peter at Berghold dot Net
       Dog trainer, dog agility exhibitor, brewer of fine Belgian style ales. Happiness is a warm, tired, contented dog curled up at your side and a good Belgian ale in your chalice.
Re: Deleting files
by sulfericacid (Deacon) on Feb 02, 2004 at 15:43 UTC
    This question has been asked a few times. If you run a general search on 'deleting files', you'll find some that talk about them depending on how long ago they were created. Here is a good node I think will help you with this: 124830.


    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid
Re: Deleting files
by welchavw (Pilgrim) on Feb 02, 2004 at 15:49 UTC

    Mark,

    You'll need to be a little clearer, since I can't tell if you want to delete files not modified within 5 days or those created more than five days from the present time. I'd guess that you mean modification time, in which case you'll need to look at the -M operator. Something like the following...

    unlink map {-M $_ > 5 ? $_ : ()} <c:/foo/*>;

    Regards,
    welchavw

    Update: Please see ysth's explanation below of why this simplistic logic is a non-starter for scripts that run for a long time.

Re: Deleting files
by ysth (Canon) on Feb 02, 2004 at 16:50 UTC
    Some have suggested using -M $filename. This will return a number of days between the file's last modification and the time your perl program started (which will be negative if the file was modified after your program started).

    This is probably what you want to check, e.g. with:

    unlink grep -f $_ && -M _ >= 5, glob "$dirname/*";
    (see -f, -M, glob, and grep in perlfunc).

    But, if your program ran today at 11:00, files modified before 11:00 5 days ago would be deleted, and files modifiedd after 11:00 would not. Your wording "older than five days from the days date" makes me think you may be asking to decide based on just the date of modification, not the time. That's a little more complex.

      Yes, true. The naive application of -M only works for the simple case of an app that doesn't run for very long. A follow-up I'm interested in is this...is localization of $^T recommended to test against the instantaneous current time?

      Regards,
      welchavw

Re: Deleting files
by broquaint (Abbot) on Feb 02, 2004 at 17:10 UTC
    You can simply provide unlink with a list of filenames as matched by your criteria, which is where File::Find::Rule becomes rather handy
    use File::Find::Rule; unlink find(file => mtime => '<='.(time - 5 * 24 * 3600), in => $dir);
    See. unlink and File::Find::Rule for more info.
    HTH

    _________
    broquaint

      In attempts to suck-up to merlyn, I used File::Finder for the first practical time today, and it totally kicks butt for things like this. The filter-chaining scheme means you can stack filters very cleanly, and it's legal to stick evals in the filter chain as well. So you can filter based on name, time, arbitrary code, etc, and then execute arbitrary code when you are done. It turns File::Find into a quite elegant one liner.

      Straight from the docs:

      my $blaster = File::Finder->atime("+30")->eval(sub { unlink });
      update: be sure you know the difference between atime, mtime, and ctime, as jacques rightfully points out below. mtime is most likely the right one in most scenarios. Chosing the wrong one will mean important things get deleted!
Re: Deleting files
by JSchmitz (Canon) on Feb 02, 2004 at 16:30 UTC
    #!/usr/bin/perl -w # # Usage: oldfiles [#months] # $monthdays = 365 / 12; # Number of days in a month $minage = $monthdays * 6; # Default Minimum Age of a file (6 months +) # # Process months argument, if any # if ($#ARGV >= 0) { $minage = $monthdays * $ARGV[0]; } # # Skate down the ole directory tree # &traverse('.'); sub traverse { local($dir) = shift; local($path); unless (opendir(DIR, $dir)) { warn "Can't open $dir\n"; closedir(DIR); return; } foreach (readdir(DIR)) { next if $_ eq '.' || $_ eq '..'; $path = "$dir/$_"; if ((-d $path) && (! -l $path)) { # non-symlink dir, enter +it &traverse($path); } elsif ((-f _) && (! -l $path)) { # plain file, but not a +symlink $age = -A $path; # get age in days if ($age > $minage) { $size = -s $path; printf "%4d days %9d bytes %s\n",int($age),$size,$path +; } } } closedir(DIR);
Re: Deleting files
by jacques (Priest) on Feb 02, 2004 at 18:36 UTC
    What do you mean by "older"?: That's the real question.

    Do you want to delete files that have been sitting on the system for more than 5 days? Or do you want to delete files that were modified more than five days ago? Or do you want to delete files that were created more than five days ago?

    You see, this isn't as simple as it seems, until you realize what you want. Unfortunately, most people here, and most people in general, will immediately assume that you are referring to modification time when you discuss a file's age, but that is not always the case.

      The files that I am talking about never get modified. They are put there when they send a fax out.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://325877]
Approved by blue_cowdawg
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2024-03-28 15:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found