In short, you find the files you want to keep, and after a -o
(short for "or") which will get all the "other" non-matching files, you can do whatever you need.
Another useful argument is -mindepth 1
, which can let you easily skip the top level (level 0).
Here is an example, initiate the tree like this:
$ mkdir a a/b; touch a/{c,d,e,keep1} a/b/{f,g,h,keep2}
$ find a/ -exec ls -gGd {} +
drwxr-xr-x 1 18 Jul 12 14:31 a/
drwxr-xr-x 1 16 Jul 12 14:31 a/b
-rw-r--r-- 1 0 Jul 12 14:31 a/b/f
-rw-r--r-- 1 0 Jul 12 14:31 a/b/g
-rw-r--r-- 1 0 Jul 12 14:31 a/b/h
-rw-r--r-- 1 0 Jul 12 14:31 a/b/keep2
-rw-r--r-- 1 0 Jul 12 14:31 a/c
-rw-r--r-- 1 0 Jul 12 14:31 a/d
-rw-r--r-- 1 0 Jul 12 14:31 a/e
-rw-r--r-- 1 0 Jul 12 14:31 a/keep1
The command you'd need to wipe all files except the "keep" ones can be:
$ find a/ -mindepth 1 -name keep1 -o -name keep2 -o \( -not -type d -exec ls -gGd {} + \)
-rw-r--r-- 1 0 Jul 12 14:31 a/b/f
-rw-r--r-- 1 0 Jul 12 14:31 a/b/g
-rw-r--r-- 1 0 Jul 12 14:31 a/b/h
-rw-r--r-- 1 0 Jul 12 14:31 a/c
-rw-r--r-- 1 0 Jul 12 14:31 a/d
-rw-r--r-- 1 0 Jul 12 14:31 a/e
As you can see, keep1
and keep2
are not in the list of arguments passed to the ls
command. Feel free to replace ls -gGd
with rm -vf
:)
You can adjust the arguments in the parentheses if you have more requirements.