Shell – Delete files based on year

filesrmshelltimestamps

I need to delete all files in a directory that were created in 2009. What command can I use to do that?

Best Answer

Most filesystems don't store the creation time of a file, so the best you can do is check the last time the file was modified.

If you have a recent version of GNU find (e.g. on Linux or Cygwin) or FreeBSD or OSX, you can directly compare the date of a file with that of another file. In addition, these versions of find can use the file creation time (called its birth time, indicated with a B) if it's available on your system. Replace B by m below to use the modification time rather than the birth time.

find /path/to/directory -newerBt '2009-01-01' ! -newerBt '2010-01-01' -type f -delete

Run it once without -delete first to make sure these are the files you want. The command above will also delete files in subdirectories; if this is not desired, add -mindepth 1 -maxdepth 1 after the directory name.

If your version of find doesn't have the -newerXY primary, you'll need to create timestamp files to mark the boundaries of the range of times you want to match.

touch -t 200901010000 /tmp/from
touch -t 201001010000 /tmp/to
find /path/to/directory -newer /tmp/from ! -newer /tmp/to -type f -exec rm {} +

Zsh's glob qualifiers can match files in a time interval, but the boundaries can only be indicated relative to the current date (e.g. N days ago).

rm /path/to/directory/*(.m+566^m+931)

You can also use timestamp files for precise dates, but you lose in terseness.

touch -t 200901010000 /tmp/from
touch -t 201001010000 /tmp/to
rm /path/to/directory/*(.e\''[[ $REPLY -nt /tmp/from && $REPLY -ot /tmp/to ]]'\')