When using sudo rm -r
, how can I delete all files, with the exception of the following:
textfile.txt
backup.tar.gz
script.php
database.sql
info.txt
When using sudo rm -r
, how can I delete all files, with the exception of the following:
textfile.txt
backup.tar.gz
script.php
database.sql
info.txt
If you don't specify
-type f
find will also list directories, which you may not want.Or a more general solution using the very useful combination
find | xargs
:for example, delete all non txt-files in the current directory:
The
print0
and-0
combination is needed if there are spaces in any of the filenames that should be deleted.The extglob (Extended Pattern Matching) needs to be enabled in BASH (if it's not enabled):
Trying it worked with:
but names with spaces are (as always) tough. Tried also with
Virtualbox\ VMs
instead the quotes. It deletes always that directory (Virtualbox VMs
).Rather than going for a direct command, please move required files to temp dir outside current dir. Then delete all files using
rm *
orrm -r *
.Then move required files to current dir.
Assuming that files with those names exist in multiple places in the directory tree and you want to preserve all of them:
Since nobody mentioned it: