Ana
Ana

Reputation: 141

Remove directories that doesn't have a subdirectory with a certain name

I would like to remove all the directories that do not have directoryB. The tree structure is like:

--directory1
         |
          directoryA---directoryB
         |
          directoryC
         |
          directoryD---directoryB

I have tried the below script within directory1:

du -a -h --max-depth=1 | sort -hr

So I know that all the directories I want to remove have a size 8k. If I tried the script below outside directory1 shows nearly everything within.

find directory1 -maxdepth 1 -type d -size 8

I think that my safe option is to remove the directories without directoryB. How can I do that?

Upvotes: 1

Views: 224

Answers (2)

oguz ismail
oguz ismail

Reputation: 50750

I don't think you need find for this. A simple loop would work just fine.

for d in directory1/*/; do
  if ! test -d "${d}directoryB"; then
    echo rm -r "${d}"
  fi
done

Remove echo if you're happy with the output.

Upvotes: 2

0stone0
0stone0

Reputation: 43894

Using find and test:

  1. find . Find in current working dir
  2. -type d only folders
  3. -depth depth-first mode [1]
  4. -depth 1 force depth to 1
  5. ! -exec test -e "{}/dirB/" \; If this file does not contain dirB
  6. -print print path
find . -type d -depth -depth 1 ! -exec test -e "{}/dirB/" \; -print

If the output seems fine, replace -print with -exec rm -r "{}" \; to remove the folders:

find . -type d -depth -depth 1 ! -exec test -e "{}/dirB/" \; -exec rm -rf {} \;

Example:

$ tree
.
|-- dirA
|   `-- dirB
|-- dirC
|   `-- dirX
`-- dirD
    `-- dirB

6 directories, 0 files
$
$
$ find . -type d -depth -depth 1 ! -exec test -e "{}/dirB/" \; -exec rm -rf {} \;
$
$ tree
.
|-- dirA
|   `-- dirB
`-- dirD
    `-- dirB

4 directories, 0 files
$

Upvotes: 1

Related Questions