In linux, how to delete all files EXCEPT a pattern?

In linux, how to delete all files EXCEPT a pattern?

Question:
In linux, how to delete all files EXCEPT a pattern?

We can delete files from a directory by specifying the file name or using patterns like *<some-identifier> [Eg: IIS*.json] to remove files from a directory.

But, how to delete all files which not matching the given pattern?

Answer:
find . -maxdepth 1 -type f \! -name "IIS*.json" -exec rm {} \;

is another way ..

In Linux, a shell pattern is a string that consists of the following special characters, which are referred to as wildcards or metacharacters:

* – matches zero or more characters
? – matches any single character
[seq] – matches any character in seq
[!seq] – matches any character not in seq

The different extended pattern matching operators are listed below, where pattern-list is a list containing one or more filenames, separated using the | character:

*(pattern-list) – matches zero or more occurrences of the specified patterns
?(pattern-list) – matches zero or one occurrence of the specified patterns
+(pattern-list) – matches one or more occurrences of the specified patterns
@(pattern-list) – matches one of the specified patterns
!(pattern-list) – matches anything except one of the given patterns
To use them, enable the extglob shell option as follows:

# shopt -s extglob

1. To delete all files in a directory except filename, type the command below:

$ rm -v !(“filename”)

2. To delete all files with the exception of filename1 and filename2:

$ rm -v !(“filename1″|”filename2”)

3. To delete all files except a specific pattern:

$ rm !(pattern)

Once you have all the required commands, turn off the extglob shell option like so:

$ shopt -u extglob