using rm *text* you can delete all files which have a certain string in them. How would I make it so that it removes every file except for the ones with the specific wildcard?
I have attempted to use other things I've found, such as:
find . -type f -print0 | xargs --null grep -Z -L 'text' | xargs --null rmor
grep -r -L -Z 'text' . | xargs --null rmbut these do not work. Instead, they are deleting all files in a given directory.
How could I do this?
22 Answers
You can do this by enabling extended globs:
shopt -s extglobNow you can do for instance
ls !(*.pdf)Or in your example
rm !(*text*) With find:
find . -type f -not -name "*text*" -exec rm {} \;Note that this will remove all files not matching the specified pattern (*text*) in the current folder and its subfolders.
If you need to remove only files found in the current folder you can use the -maxdepth 1 flag:
find . -maxdepth 1 -type f -not -name "*text*" -exec rm {} \;