Linux/shell - Remove all (sub)subfolders from a directory except one

374 views Asked by At

I've inherited a structure like the below, a result of years of spaghetti code...

gallery
├── 1
│   ├── deleteme1
│   ├── deleteme2
│   ├── deleteme3
│   └── full
│       ├── file1
│       ├── file2
│       └── file3
├── 2
│   ├── deleteme1
│   ├── deleteme2
│   ├── deleteme3
│   └── full
│       ├── file1
│       ├── file2
│       └── file3
└── 3
    ├── deleteme1
    ├── deleteme2
    ├── deleteme3
    └── full
        ├── file1
        ├── file2
        └── file3

In reality, this folder is thousands of subfolders large. I only need to keep ./gallery/{number}/full/* (i.e. the full folder and all files within, from each numbered directory within gallery), with everything else no longer required and needs to be deleted.

Is it possible to construct a one-liner to handle this? I've experimented with find/maxdepth/prune could not find an arragement which met my needs.

(Update: To clarify, all folders contain files - none are empty)

3

There are 3 answers

0
salvarez On BEST ANSWER

Using PaddyD answer you can first clean unwanted directories and then delete them:

find . -type f -not -path "./gallery/*/full/*" -exec rm {} + && find . -type d -empty -delete
0
that other guy On

This can easily be done with bash extglobs, which allow matching all files that don't match a pattern:

shopt -s extglob
rm -ri ./gallery/*/!(full)
2
PaddyD On

How about:

find . -type d -empty -delete