I want to remove all the folders and files but except one. I have a Ubuntu server and I tried several methods and none of them worked.
This is my folder structure.
app
app/public
app/public/uploads
app/public/css
app/models
file.txt
I want to keep the app/public/uploads
and delete all other files and folders.
These are the methods I tried:
find . -maxdepth 1 ! -name 'public/uploads' ! -name '.*' | xargs rm -rf
find . ! -name 'public/uploads' -type f -exec rm -f {} +
Best Answer
I actually wanted to achieve a similar behaviour today. I'm wiring documentation for a C# library that I have written with DocFx and the files were generated inside the
_site
folder.Now, in my particular case, I needed two things, a) to have a git repository inside the
_site
folder, and b) after each build I wanted to remove everything inside the_site
folder except the.git
folder and all its contents.To simulate the behaviour lets see the following structure:
The goal is to remove all except
.git/**
So first, what I did was to write a
find .
command and see what I'm getting:Then I wrote
find . -mindepth 1 -not -regex "^\./\.git.*"
to exclude the.git
folder and all its contents:Now that I'm happy with the results, all I had to do is to pass the
-delete
flag to my find command, resulting infind . -mindepth 1 -not -regex "^\./\.git.*" -delete
:In case you
find
command does not support-delete
flag, then you can achieve the same result withfind . -mindepth 1 -not -regex "^\./\.git.*" -print0 | xargs -0 -I {} rm -rf {}
For my case though, I want to run the command outside of the
_site
folder; thus, my final command looks like so:find ./_site -mindepth 1 -not -regex "^\.\/_site\/\.git.*" -delete
That could also work:
find ./_site -mindepth 1 -not -regex "^.*\/.git.*" -delete
, but it would also preserve any.git
folder you may have in any subfolder of the folder you want to clean up.I hope it helps!
Cheers!