Roger
Roger

Reputation: 29

How to keep certain folders and delete rest in Unix

I have around 10 folders and I am trying to keep only few subfolders under these and delete the rest.

Example: I have

A/1
A/2
A/3 
A/4

B/1
B/4
B/5
B/6

I am trying to keep only the folder 1 and 4 under each parent folder A and B. I am using find -type d -name 2 -exec rm -rf {} \; to find and delete each folder.

Is there any unix command to just keep the folder 1 and 4 and delete the rest?

Upvotes: 0

Views: 245

Answers (4)

Diego Torres Milano
Diego Torres Milano

Reputation: 69208

Using just glob

$ rm -rf [AB]/[^14]

Upvotes: 0

Jeff Y
Jeff Y

Reputation: 2456

AIG's idea to exclude is probably correct, but the way to exclude with find is with the -o (or) operator, which stops if what came before is true and continues otherwise:

find . -mindepth 2 -type d -name 1 -o -name 4 -o -exec rm -rf {} +

Upvotes: 1

grymoire
grymoire

Reputation: 27

I believe this works for posix compliant systems:

find . -type d -links 2 \! \( \( -name 1 \) -o \( -name 4 \) \) -exec rm -rf {} \;

This includes only child directories and excludes directories named 1 or 4.

Upvotes: 0

AlG
AlG

Reputation: 15157

Tell find exactly what you are looking for;

find . -mindepth 2 -type d -name "[^14]" -exec rm -rf {} \;

Excluding directories 1 and 4, at the child level, find the other directories and delete them.

Upvotes: 1

Related Questions