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?

  • Will the exceptions always be a single letter? Aug 3, 2016 at 4:59
  • That's the name of my folder. I named them a and b. Just for testing! Not always single letter, maybe hyphen or sth else.
    – The One
    Aug 3, 2016 at 5:03
  • I get that but I asked if the answer should rely on the fact that they are a single letter or not? If not, what would the criteria be to exclude them? Aug 3, 2016 at 5:04
  • Keep in mind that computer do not yet have mind reading technology and you need to tell the computer exactly what you want done. In your simple example, I would use rm ??* which would ignore single letter names. Aug 3, 2016 at 5:06
  • Ah, i see that :D
    – The One
    Aug 3, 2016 at 6:56

2 Answers 2


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 {} \;

I use this command to delete all (including hidden) except selected files/folders in the CURRENT directory.

find . -maxdepth 1 ! -name "file1.php" ! -name "file2.js" ! -name "dir1" ! -name "dir2" ! -name . -exec rm -r {} \;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .