5

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 rm

or

grep -r -L -Z 'text' . | xargs --null rm

but these do not work. Instead, they are deleting all files in a given directory.

How could I do this?

2

2 Answers 2

8

You can do this by enabling extended globs:

shopt -s extglob

Now you can do for instance

ls !(*.pdf)

Or in your example

rm !(*text*)
3

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 {} \;

Not the answer you're looking for? Browse other questions tagged .