Home > Blockchain >  How do you remove an entire directory except for certain subdirectories in linux?
How do you remove an entire directory except for certain subdirectories in linux?

Time:06-16

Suppose I run the following command in linux:

$ mkdir -p mp3 jpeg/dir1 jpeg/dir2 txt
$ touch mp3/1.mp3 mp3/2.mp3 mp3/3.mp3
$ touch jpeg/1.jpeg jpeg/2.jpeg jpeg/3.jpeg
$ touch txt/1.txt txt/2.txt txt/3.txt

This will create a directory structure like:

├── jpeg
│   ├── 1.jpeg
│   ├── 2.jpeg
│   └── 3.jpeg
│   └── dir1
│   └── dir2
├── mp3
│   ├── 1.mp3
│   ├── 2.mp3
│   └── 3.mp3
└── txt
    ├── 1.txt
    ├── 2.txt
    └── 3.txt

How do I invoke the linux "rm" command to remove everything in the "jpeg" directory except for "dir2" subdirectory?

So I'm looking for a command that looks something like:

rm -rf -not dir2 jpeg

But when I run that command on Centos 7, I get the following error message:

rm: invalid option -- 'n'

My target output directory structure should look like:

├── jpeg
│   
│   
│   
│   
│   └── dir2
├── mp3
│   ├── 1.mp3
│   ├── 2.mp3
│   └── 3.mp3
└── txt
    ├── 1.txt
    ├── 2.txt
    └── 3.txt

Would appreciate all/any help from the linux scripting community

CodePudding user response:

You can use this find command to delete everything in jpeg directory except dir2:

find jpeg -mindepth 1 -not -path 'jpeg/dir2' -prune -delete
  • Related