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?

chaps
  • 53
  • 1
  • 5
  • 1
    Bash extended globbing (`extglob`) provides a negation operator - see for example [How to delete all files except one named file from a specific folder](https://askubuntu.com/questions/624441/how-to-delete-all-files-except-one-named-file-from-a-specific-folder) – steeldriver Sep 28 '19 at 11:01
  • 2
    FWIW the issue with your `find` attempts is that they grep for the names of files whose *contents* do not match `text` – steeldriver Sep 28 '19 at 11:25

2 Answers2

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*)
vidarlo
  • 21,954
  • 8
  • 58
  • 84
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 {} \;
BeastOfCaerbannog
  • 12,964
  • 10
  • 49
  • 77