1

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 {} \;
cuonglm
  • 153,898

4 Answers4

1

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.

Stephen Kitt
  • 434,908
1
find ./* -prune ! -path './xfer' -exec rm -fr {} +

More correct (but GNU):

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

or

find . ! -path './xfer' ! -path '.xfer/*' -delete
Costas
  • 14,916
0

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

YoMismo
  • 4,015
0

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.

frostschutz
  • 48,978