Delete all files except a pattern

Hello,

Have a folder with lots of files & directories.
Want to delete all stuff except a particular pattern say "abc*".
Pattern will be in base directory & descending the structure is not required.

Can easily do it with looping or "grep -v", but wondering if there is an elegant solution.

Try this:

 
# ls -ltrR
.:
total 24
-rw-r--r--  1 root root    0 Feb  7 13:51 bin.sh
drwxr-xr-x  2 root root 4096 Feb  7 14:10 bneo
-rw-r--r--  1 root root    0 Feb  7 14:15 script.txt
-rw-r--r--  1 root root    0 Feb  7 14:15 neo
-rw-r--r--  1 root root    0 Feb  7 14:15 eon.sh
./bneo:
total 8
-rw-r--r--  1 root root 0 Feb  7 14:10 neo.sh
-rw-r--r--  1 root root 0 Feb  7 14:10 bin.sh

# find . -maxdepth 1 ! \( -name "bin*" -o -name '.' -o -name '..' \) -print
./neo
./script.txt
./eon.sh
./bneo

Instead of print, if you will pass

-exec rm {} \;

; it will delete the files in the present directory. Mind it that since I have not passed rm -rf, the directory will not be deleted.

So if you want to delete everything (non matching files n folders) , do this:

 
# find . -maxdepth 1 ! \( -name "bin*" -o -name '.' -o -name '..' \) -exec rm -rf {} \;
# ls -ltr
total 4
-rw-r--r--  1 root root 0 Feb  7 13:51 bin.sh

Checkout extended globbing in ksh93/bash

ls !(abc*)

In bash first execute the following command if extended globbing is not on by default

shopt -s extglob

You can check if it's on with the command shopt

Thanks

I may be mistaken, but believe that "find" may take subsequent time in making the list & passing it off to the -exec call. Though we have given the maxdepth option.

Directories what i plan to cleanup belong in range of 300GB.

Do correct if mistaken.

---------- Post updated at 03:24 PM ---------- Previous update was at 03:23 PM ----------

Yup, I tried that & was pretty effective.
Limitation being it works with only a single pattern.

Is there a way to make it work for more than 1 pattern?

try:

ls !(abc*|xyz*)

Thanks that works.

Thoughts on which will be the better approach.
Find or the shopt.

My vote is to shopt :slight_smile: