Delete files based on date and time in Linux, Unix, or Mac OS X

I want to all the files in a directory based on the date and time they were created using the terminal command line.

Why? Today I got 9,000 messages to one of my email inbox folders. Luckily our mail servers are IMAP on a Linux system and all of the messages went into the same folder. Each individual email has its own file. Rather than use my email client, I wanted to craft a command to delete all of the files in a folder that were created within the last 12 hours.

With some searching I found a post to Delete files based on date. With some modification, I found that this command works for me in Ubuntu to delete files from today (3/27/08):

rm -vi `ls -lh | sed -n '/2008-03-27/p' | awk '{print $8}'`

How it works

This command gives the list of files that fit the date. Broken down:

ls -lh is a standard file list

sed -n '/2008-03-27/p' displays only the files that have the date specified from the ls output.

If I want to delete files at 1AM on 2008-3-27 I can do this:

sed -n '/2008-03-27 01/p'

To grab the filename I take the 8th element from the ls output using awk.

awk '{print $8}' 

I double-checked to make sure that the list is OK. Now we delete! To be sure, we can do an interactive verbose delete to make sure the delete isn’t killing the wrong files. As a test, I delete all the files from 10AM this morning:

rm -vi `ls -lh | sed -n '/2008-03-27 10/p' | awk '{print $8}'`

It looks OK, so now I can delete all of the files from today’s date. Since the file list was too long so I guess I have to delete them hour -by-hour. It works fine for decently large lists.

Syndicate content