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
You can do this with two command sequences. First define an array with the name of the files you do not want to exclude:
After that, loop through all files in the directory you want to exclude, checking if the filename is in the array you don't want to exclude; if its not then delete the file.
You can write a for loop for this... %)
A little late for the OP, but hopefully useful for anyone who gets here much later by google...
I found the answer by @awi and comment on -delete by @Jamie Bullock really useful. A simple utility so you can do this in different directories ignoring different file names/types each time with minimal typing:
rm_except (or whatever you want to name it)
e.g. to delete everything except for text files and foo.bar:
Similar to @mishunika, but without the if clause.
Just:
Or:
This is similar to the comment from @siwei-shen but you need the
-o
flag to do multiple patterns. The-o
flag stands for 'or'find . -type f -not -name '*ignore1' -o -not -name '*ignore2' | xargs rm
find . | grep -v "excluded files criteria" | xargs rm
This will list all files in current directory, then list all those that don't match your criteria (beware of it matching directory names) and then remove them.
Update: based on your edit, if you really want to delete everything from current directory except files you listed, this can be used:
It will create a backup directory
/tmp_backup
(you've got root privileges, right?), move files you listed to that directory, delete recursively everything in current directory (you know that you're in the right directory, do you?), move back to current directory everything from/tmp_backup
and finally, delete/tmp_backup
.I choose the backup directory to be in root, because if you're trying to delete everything recursively from root, your system will have big problems.
Surely there are more elegant ways to do this, but this one is pretty straightforward.