LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to delete all folders and their contents except 3 (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-delete-all-folders-and-their-contents-except-3-a-785348/)

anon091 01-28-2010 08:17 AM

How to delete all folders and their contents except 3
 
I have a USB drive that has a TON of folders on its root level. I want to remove all those folders and their contents except three of them. I know if I do rm -rf that will kill everything, is there a way to exclude three folders, say folder1 folder2 newfolder, and do it all in one statement?

Web31337 01-28-2010 08:36 AM

Code:

mv dir1 dir2 dir3 /some/backup/dir
rm -rf ./

why waste time? it will also save you data in case you do it wrong.
well, in fact you can use rm with ls --hide if you wish.

pixellany 01-28-2010 08:39 AM

Trying to write simple code to do something like this will be "fragile"---meaning that you have to be very careful in how you specify things.

Here's a simple example of the kind of thing that might work, but it's just using rm for files. TEST any code before actually using on real data.

Code:

rm $(ls|egrep -v "(file1|file2)")  ##removes everything except file1 and file2

anon091 01-28-2010 08:41 AM

thanks pixellany, I figured there would be some way to do it other than moving all my folders i want to keep to another location. I'll have to look into it to see if i can figure out how to make it keep only certain folders at that root level.


All times are GMT -5. The time now is 04:37 AM.