delete file older than x days

merlin's picture

They have: 410 posts

Joined: Oct 1999

i'm getting into it, slowly... but, another question:
i'd like to delete all files in a directory, which are older than, let's say, 20 days.
that's what i have:

foreach $file (@postcarddata) {
if (-M $file > 20) {
print "$file<br>";
unlink $file;
}
}
'

another thing i tried:

foreach $file (@postcarddata) {
next unless -M $file > 12;
unlink $file;
}
'

but well, it's not really working... what am i doing wrong? thanx for your help!

They have: 161 posts

Joined: Dec 1999

You should be testing the return value of unlink() -- maybe then, you'll have a better idea of why it's not working. It works for me:

opendir DIR, $path or die "can't read $path: $!";
while (defined(my $file = readdir DIR)) {
  # use the path to the file, not just the name of the file
  next unless -f "$path/$file";
  if (-M "$path/$file" >= 7) {
    # delete if a week old
    unlink "$path/$file" or warn "can't delete $path/$file: $!";
  }
}
closedir DIR;
'

merlin's picture

They have: 410 posts

Joined: Oct 1999

that worked! i didn't give the path of the file, that's what i made wrong, probably...
anyway, now it's working and it's great! thanks japhy!

They have: 117 posts

Joined: Mar 2000

Just wondering, how would you delete all files that haven't been modified within x number of days?

--Edge

They have: 161 posts

Joined: Dec 1999

Well, now I feel kinda silly. The code I'd posted was for files that have not been updated in X days. So that answers your question, Edge.

You can't get at the creation time of files, alibababa, so the code you're using is testing for when the file was last modified. That might be what you wanted, though.

merlin's picture

They have: 410 posts

Joined: Oct 1999

thanks japhy, you told me what i was looking for. and beside, the hard thing (at least for me) is the syntax. for changing the file-selection i only have to change the letter (-A, -C, -M).

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.