How to delete all except for some specific folder under parent-folder

command linedelete

So here's content under my /html folder.

[root@ip-10-0-7-121 html]# ls
a             wp-activate.php       wp-content         wp-mail.php
b             wp-admin              wp-cron.php        wp-settings.php
healthy.html  wp-blog-header.php    wp-includes        wp-signup.php
index.php     wp-comments-post.php  wp-links-opml.php  wp-trackback.php
license.txt   wp-config.php         wp-load.php        xmlrpc.php
readme.html   wp-config-sample.php  wp-login.php

I want to delete everything except for folder a and b without having to move a/b folder to another folder.
What's the command to do that?

Best Answer

You can use find with a negation (at your own risk).

find all file and folders named "a" or "b":

find -name a -o -name b

find all files and folders name "a" or "b" in the current directory"

find -maxdepth 1 -name a -o -name b

find all files and folders not named "a" and not named "b" in current directory:

find -maxdepth 1 ! -name a ! -name b

also exclude current directory from result

find -maxdepth 1 ! -name a ! -name b ! -name .

now you can use rm to delete all founded elements:

find -maxdepth 1 ! -name a ! -name b ! -name . -exec rm -rv {} \;
Related Question