rm: delete files before (or after) a specific date

Sometimes I have to delete files before or after a specific date. Here is a one liner to do this:

Delete files after a specific date

Executing the following lines results in deletion of files last changed after 01-01-2017 00:00

touch -t 201701010000 /tmp/ref
find /path/to/files -type f -newer /tmp/ref | xargs -r rm -f
rm /tmp/ref

What this does: touch generates the file /tmp/ref and sets its last modification date to 01-01-2017 00:00 where the format is YYYYMMDDHHMM. Afterwards find compares the last modification date of all files in /path/to/files to the last modifiction date of /tmp/ref that we just set. All files that where found are given to xargs via pipe. xarg builds and executes command lines to delete the files. Last the temporary file that was used for date comparision is deleted.

Combining this to the promised ready to copy and paste one liner:

touch -t YYYYMMDDHHMM /tmp/ref && find /path/to/files -type f -newer /tmp/ref | xargs -r rm -f && rm /tmp/ref

Don’t forget to adjust YYYYMMDDHHMM and /path/to/files (use . for current directory) to your needs.

Delete files before a specific date

Deleting files before a specific date is pretty much the same. Just put a ! in front of the -newer argument.

touch -t 201701010000 /tmp/ref
find /path/to/files -type f ! -newer /tmp/ref | xargs -r rm -f
rm /tmp/ref

Combining this to a ready to copy and paste one liner:

touch -t YYYYMMDDHHMM /tmp/ref && find /path/to/files -type f ! -newer /tmp/ref | xargs -r rm -f && rm /tmp/ref

Again: Don’t forget to adjust YYYYMMDDHHMM and /path/to/files (use . for current directory) to your needs.

Tagged with: , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*