Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I delete all files that don't start with "2012" in a particular folder?

This is on OS X Lion.

share|improve this question

Use find to select all files (type f) that don't (!) start with 2012 ("2012*"). You then rm (remove) them right away, or let the delete switch do that for you.

find . -type f ! -name "2012*"

Note that this recursively descends into subdirectories. If you want to be sure that you don't remove stuff you actually want to keep, make sure to use the right options (so check out man find for more).

For example, -maxdepth 1 will not go into subdirectories.

Now, remove those files:

find . -type f ! -name "2012*" -delete
share|improve this answer
Or find . -type f ! -name "2012*" -delete. Implies -depth, but that doesn't make a difference for file matches only. – Daniel Beck May 2 '12 at 10:29
For some reason I thought -delete was GNU-only. Changed that, it's safer anyway. – slhck May 2 '12 at 10:30
I had to double-checked as well. BSD/GNU differences confuse me every time. – Daniel Beck May 2 '12 at 10:33
Or instead of -delete you could pipe into rm. – Scott Wilson May 2 '12 at 10:45
@ScottWilson No, the whole point of delete is to be efficient and secure. You could use -exec rm, which is somewhat safe, but as a general rule: If you're piping find output into something else, you're doing something wrong (the command is unsafe by default, and probably not portable). Please read Finding Files. – slhck May 2 '12 at 10:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .