Home > Enterprise >  Retaining one sub directory and deleting everything else
Retaining one sub directory and deleting everything else

Time:10-09

Directory structure:

/parent/
/parent/child1/
/parent/child2/
.
.
.
/parent/child1/sub1/sub2/sub3/
/parent/child1/subA/subB/
/parent/child1/subX/subY/
.
.
.
/parent/child1/subX/subY/subZ/
/parent/child1/subA/subB/

I want to keep:

parent/child1/sub1/sub2/sub3/

and delete everything else in the parent folder

I have tried

find ./parent -mindepth 1  -type d -not -path "*/sub3*" -exec rm -rf {} \;

But it still ends up deleting the /parent/child2/sub1/sub2/ directory.

CodePudding user response:

Try using find's built in -delete:

find ./parent -not -path "*/sub3*" -delete

Example:

% mkdir -p /tmp/foo/{1..5}/sub{1..35}
% touch /tmp/foo/{1..5}/{bar,sub{1..35}/more.bar}
% find /tmp/foo -not -path '*/sub3*' -delete
% find /tmp/foo | head
/tmp/foo
/tmp/foo/1
/tmp/foo/1/sub32
/tmp/foo/1/sub32/more.bar
/tmp/foo/1/sub35
/tmp/foo/1/sub35/more.bar
/tmp/foo/1/sub34
/tmp/foo/1/sub34/more.bar
/tmp/foo/1/sub33
/tmp/foo/1/sub33/more.bar

In your solution you use "rm -rf {}" which, at some point, will call:

rm -rf ./parent/childN
  • Related