0

I need to delete all sub directories and their contents in a given folder, whilst leaving a particular sub directory. Is there a way to do this using bash or a shell script? The file structure is shown below.

container_dir
│
├── delete_this_dir
│   ├── file1.txt
│   └── file2.txt
│
├── delete_this_dir
│   ├── l1.txt
│   └── l2.txt
│
└── keep_this_dir
    ├── file1.txt
    ├── file2.txt
    └── file3.txt
Anthon
  • 78,313
  • 42
  • 165
  • 222
S tommo
  • 3
  • 1

3 Answers3

1

In bash, use extglob to exclude the directory you want to keep:

shopt -s extglob
rm -rf container_dir/!(keep_this_dir)
Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
0

Backup this container_dir and try this:

find $container_dir/* -path $keep_this_dir -prune -o -name "*" -type d -exec rm -rfv {} \;

But I recommend to use simpler solution with backup

mrc02_kr
  • 1,973
  • 17
  • 31
0

If it is only name by which you identify what directory to keep, then you could do as follows:

cd container_dir && \
find . -maxdepth 1 -type d ! -name . ! -name keep_this_dir -exec rm -r {} +

Meaning, change over to the container dir, then launch a find from there but only till depth levels of 1 and search only amongst directories at that level. From this pool of directories that find acquires, keep off just two, viz., the container_dir and the keep_this_dir. Rest all to be culled.