12

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?

David Oneill
  • 12,502
  • 16
  • 58
  • 70

2 Answers2

24

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
  • 9,581
  • 5
  • 40
  • 46
  • 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 Sep 09 '10 at 13:25
  • 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 Sep 09 '10 at 13:25
  • 1
    oh yes sorry, there shouldn't be a -f, just f. – bramp Sep 09 '10 at 13:27
  • 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 Sep 09 '10 at 13:29
  • never mind my previous comment. It is only showing the older ones. Thanks! – David Oneill Sep 09 '10 at 13:29
  • Is there a way to delete files modified *after* a given date? It lists them fine without the "!" in `find /path/to/files -type f -newer dummyfile` but `-delete` doesn't work. Passing the output into a `for` loop with `rm` did the trick but there's an easier way, right? – Tom Kelly Jun 04 '17 at 12:59
  • If your `find` lacks the `-delete` option, try `-exec rm {} +` or if your `find` also doesn't support `-exec` with `+`, try `\;` instead of `+`. – tripleee Dec 26 '21 at 12:17
9

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
  • 43,147
  • 9
  • 68
  • 92
  • Eric, what version of find has "newerct". I can't find that listed on any man page. – bramp Sep 09 '10 at 13:30
  • @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 Sep 09 '10 at 13:50