tags:

views:

43

answers:

2

I have a folder with a bunch of files. I need to delete all the files created before July 1st. How do I do that in a bash script?

+5  A: 

I think the following should do what you want:

touch -t 201007010000 dummyfile
find /path/to/files -type f ! -newer dummyfile -delete

The first line creates a file which was last modified on the 1st July 2010. The second line finds all files in /path/to/file which has a date not newer than the dummyfile, and then deletes them.

If you want to double check it is working correctly, then drop the -delete argument and it should just list the files which would be deleted.

bramp
After dropping the `-` in front of 'f', it now seems to list all the files. If I drop the '!' it only lists the newer files.
David Oneill
I shamelessly stole/altered the answer from http://forums.devshed.com/unix-help-35/finding-a-file-modified-created-before-a-specific-date-468700.html
bramp
oh yes sorry, there shouldn't be a -f, just f.
bramp
I just double checked (and ran a quick test) and the correct command is indeed: find /path/to/files -type f ! -newer dummyfile -delete
bramp
never mind my previous comment. It is only showing the older ones. Thanks!
David Oneill
+1  A: 

This should work:

find /file/path ! -newermt "Jul 01"

To find the files you want to delete, so the command to delete them would be:

find /file/path ! -newermt "Jul 01" -type f -print0 | xargs -0 rm
Eric Wendelin
Eric, what version of find has "newerct". I can't find that listed on any man page.
bramp
@bramp: GNU `find` has that option. However, Unix/Linux has no notion of a creation date, so I would use `-newermt`. The `c` is for the status change of the inode rather than "creation".
Dennis Williamson
@Dennis: Thank you for your clarification.
Eric Wendelin