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
Since no one yet mentioned this, in one particular case:
(or just
rm $OLD_FILES
)or
You may need to use
shopt -s nullglob
if some files may be either there or not there:without nullglob,
echo *.sh *.bash
may give you "a.sh b.sh *.bash".(Having said all that, I myself prefer this answer, even though it does not work in OSX)
You can use GLOBIGNORE environment variable in Bash.
Suppose you want to delete all files except php and sql, then you can do the following -
Setting GLOBIGNORE like this ignores php and sql from wildcards used like "ls *" or "rm *". So, using "rm *" after setting the variable will delete only txt and tar.gz file.
If you're using
zsh
which I highly recommend.With
extended_glob
Make the files immutable. Not even root will be allowed to delete them.
All other files have been deleted.
Eventually you can reset them mutable.
I prefer to use sub query list:
Remove everything exclude file.name: