Today I Learned: 26/05/2022 - Deleting a large set of directories for a given year
Publish date: 26 May 2022
I recently needed to delete a large set of directories on a server, which had piled up in a non-emptied cache. To avoid breaking things, I wanted to delete the oldest files first as a test, which were from 2019. One way to delete a set of directories that were last modified in 2019 is this find invocation, executed in the directory holding the offending files:
find . -maxdepth 1 -type d -newermt 2019-01-01 ! -newermt 2020-01-01 -exec rm -rf {} \;
- The -maxdepth 1 argument limits return values to the top level directories - as they’re being deleted going through their contents is not necessary.
- The first -newermt arguments specify the earliest last-modified-time to consider
- The second -newermt argument is negated with the ! and so specifies the latest last-modified-time to consider
- The results are passed to rm -rf in the {} piece