Search code examples
bashfindls

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?


Solution

  • 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.