Reputation: 141
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
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
Reputation: 43894
find .
Find in current working dir-type d
only folders-depth
depth-first mode [1]-depth 1
force depth to 1! -exec test -e "{}/dirB/" \;
If this file does not contain dirB
-print
print pathfind . -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