Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all files/directories except two specific directories

Tags:

python

linux

bash

So, there seems to be a few questions asking about removing files/directories matching certain cases, but I'm looking for the exact opposite: Delete EVERYTHING in a folder that DOESN'T match my provided examples.

For example, here is an example directory tree:

.
|-- coke
|   |-- diet
|   |-- regular
|   `-- vanilla
|-- icecream
|   |-- chocolate
|   |-- cookiedough
|   |-- cupcake
|   |   |-- file1.txt
|   |   |-- file2.txt
|   |   |-- file3.txt
|   |   |-- file4.txt
|   |   `-- file5.txt
|   `-- vanilla
|-- lol.txt
|-- mtndew
|   |-- classic
|   |-- codered
|   |-- livewire
|   |   |-- file1.txt
|   |   |-- file2.txt
|   |   |-- file3.txt
|   |   |-- file4.txt
|   |   `-- file5.txt
|   `-- throwback
`-- pepsi
    |-- blue
    |-- classic
    |-- diet
    `-- throwback

I want to delete everything but the files in test/icecream/cupcake/ and test/mtndew/livewire/. Everything else can go, including the directory structure. So, how can I achieve this? Languages I wouldn't mind this being in: bash or python.

like image 673
phuzion Avatar asked May 14 '09 09:05

phuzion


People also ask

How do I delete all files except a specific file extension?

Highlight all the files you want to keep by clicking the first file type, hold down the Shift key, and click the last file. Once all the files you want to keep are highlighted, on the Home Tab, click Invert Selection to select all other files and folders.

How do I select all except one folder?

Select multiple files or folders that are not grouped together. Click the first file or folder, and then press and hold the Ctrl key. While holding Ctrl , click each of the other files or folders you want to select.


1 Answers

This command will leave only the desired files in their original directories:

find test \( ! -path "test/mtndew/livewire/*" ! -path "test/icecream/cupcake/*" \) -delete

No need for cpio. It works on Ubuntu, Debian 5, and Mac OS X.

On Linux, it will report that it cannot delete non-empty directories, which is exactly the desired result. On Mac OS X, it will quietly do the right thing.

like image 66
Patrick Webster Avatar answered Nov 10 '22 17:11

Patrick Webster