Manuel Barbe
Manuel Barbe

Reputation: 2164

Listing files that are older than one day in reverse order of modification time

In order to write a cleanup script on a directory, I need to take look at all files that are older than one day. Additionally, I need to delete them in reverse order of modification time (oldest first) until a specified size is reached.

I came along with the following approach to list the files:

find . -mtime +1 -exec ls -a1rt {} +

Am I right, that this does not work for a large number of files (since more than one 'ls' will be executed)? How can I achieve my goal in that case?

Upvotes: 0

Views: 114

Answers (2)

JuniorCompressor
JuniorCompressor

Reputation: 20025

You can use the following command to find the 10 oldest files:

find . -mtime +1 -type f -printf '%T@ %p\n' | sort -n | head -10 | awk '{print $2}'

The steps used:

  • For each file returned by find, we print the modification timestamp along with the filename.
  • Then we numerically sort by the timestamp.
  • We take the 10 first.
  • We print only the filename part.

Later if you want to remove them, you can do the following:

rm $(...)

where ... is the command described above.

Upvotes: 2

mti2935
mti2935

Reputation: 12027

Here is a perl script that you can use to delete the oldest files first in a given directory, until the total size of the files in the directory gets down to a given size:

&CleanupDir("/path/to/directory/", 30*1024*1024);  #delete oldest files first in /path/to/directory/ until total size of files in /path/to/directory/ gets down to 30MB

sub CleanupDir {
  my($dirname, $dirsize) = @_;
  my($cmd, $r, @lines, $line, @vals, $b, $dsize, $fname);

  $b=1;
  while($b) {
    $cmd="du -k " . $dirname . " | cut -f1";
    $r=`$cmd`;
    $dsize=$r * 1024;

    #print $dsize . "\n";

    if($dsize>$dirsize) {
      $cmd=" ls -lrt " . $dirname . " | head -n 100";
      $r=`$cmd`;
      @lines=split(/\n/, $r);
      foreach $line (@lines) {
        @vals=split(" ", $line);
        if($#vals>=8) {
         if(length($vals[8])>0) {
            $fname=$dirname . $vals[8];
            #print $fname . "\n";
            unlink $fname;
          }
        }
      }
    } else {
       $b=0;
    }
  }
}

Upvotes: 1

Related Questions