Delete all files except a certain file under the shell

The easiest way is

# shopt -s extglob (open extglob mode)
# rm -fr !(file1)

If there are multiple to be excluded, you can do this:
# rm -rf !(file1|file2)



BashShell has an extglob option, After opening, Shell can additionally recognize 5 pattern matching operators, which can make file matching more convenient.
Turn on the shopt command: shopt -s extglob
Turn off the shopt command: shopt -u extglob

?(pattern-list) - the given pattern is matched 0 or 1 times; *(pattern-list) - the given pattern is matched more than 0 times including 0 times ;+(pattern-list) - matches the given pattern more than 1 time including 1; @(pattern-list) - matches the given pattern only once; !(pattern-list) - does not match the given pattern in parentheses.

Example
To delete files whose filenames do not end in jpg:
rm -rf !(*jpg)
Delete files whose filenames end in jpg or png:
rm -rf *@(jpg|png)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326940393&siteId=291194637