7

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?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
The One
  • 4,662
  • 11
  • 29
  • 35

2 Answers2

18

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 {} \;
Scantlight
  • 771
  • 1
  • 7
  • 14
0

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