Recursively delete all files except some specific types

I want to recursively delete all files in some folders, except for those that have the .gz extension. I usually use

find /thepath -name "foo" -print0 | xargs -0 rm -rf

to recursively delete all folders named "foo" in / path. But now I decided to add an exception. How is this possible?

For example, the folder structure looks like

 .hiddenfolder
 .hiddenfolder/bin.so
 arc.tar.gz
 note.txt
 sample

So I want to delete everything except arc.tar.gz

+4
source share
2 answers

Find and delete all files in the / thepath directory, except with the matching * .gz names:

# First check with ls -l
find /thepath -type f ! -name '*.gz' -print0 | xargs -0 ls -l

# Ok: delete
find /thepath -type f ! -name '*.gz' -print0 | xargs -0 rm -vf

Oh, and delete all empty directories on the left:

find /thepath -type d -empty -print0 | xargs -0 rmdir -v
+5
source

I think,

find /thepath -name "foo" ! -name "*.gz" -print0

must contain the correct list of file names, but before passing the result to the command xargs, perform the actual deletion.

+2
source

All Articles