This question already has an answer here:

I'm trying to automate some file house keeping I do pretty often. I want to delete all of the files and folders in a directory while excluding the folder "./xfer" and its contents.

I've bee trying to do it using the find command but it is turning out a bit clunky. Is there a better way? I set up my test environment by running:

mkdir test0{1..5}; find . -type d -exec touch '{}'/test-0{1..5} \;

Here is the command I've been working on. Btw I am somewhat new and am mostly doing this as a learning exercise. Also, this would be the last command of a small script I am almost done with.

find /some/directory/path/* -type f ! -path "/some/directory/path/xfer/*" -exec rm -fv {} \;; find /some/directory/path/*  -type d ! -path "/some/directory/path/xfer" -exec rm -rfv {} \;

marked as duplicate by cuonglm, Anthon, X Tian, PersianGulf, chaos Jun 2 '15 at 20:09

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


You can use -prune:

find . -path ./xfer -prune -o -exec rm -fv {} \;

When listing the files, if the path matches ./xfer the file is pruned, otherwise rm is called.

find ./* -prune ! -path './xfer' -exec rm -fr {} +

More correct (but GNU):

find . -mindepth 1 -maxdepth 1 ! -name 'xfer' -exec rm -fr {} +


find . ! -path './xfer' ! -path '.xfer/*' -delete

What about a for loop? for i in $(ls|grep -v xfer);do rm -r $i;done


Maybe not what you're looking for, but that's how I usually do it. I move the stuff I want to keep out of the way.

mv dir/keepme tmp/keepme
rm -rf dir/*
mv tmp/keepme dir/keepme

Careful to stay within the same filesystem so mv does not copy/delete.

Not the answer you're looking for? Browse other questions tagged or ask your own question.