1

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 {} + 

2 Answers 2

3

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:

enter image description here

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:

enter image description here

Then I wrote find . -mindepth 1 -not -regex "^\./\.git.*" to exclude the .git folder and all its contents:

enter image description here

Now that I'm happy with the results, all I had to do is to pass the -delete flag to my find command, resulting in find . -mindepth 1 -not -regex "^\./\.git.*" -delete:

enter image description here

In case you find command does not support -delete flag, then you can achieve the same result with find . -mindepth 1 -not -regex "^\./\.git.*" -print0 | xargs -0 -I {} rm -rf {}

Be warned, don't use `-delete` or `-print0 | xargs -0 -I {} rm -rf {}` if you first don't verify that the output you are getting from `find` command matches your expectations, otherwise, you will lose data. 

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!

1

You can do this by using the command rm -r !(app/public/uploads). Let me know if this works.

Source:

2
  • I tired but it's not working Commented Mar 31, 2016 at 9:52
  • This is working for me, try getting into app/public and use the command Commented Mar 31, 2016 at 9:53

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.