One of my colleagues once asked me this question: how do I delete all files in the directory except some files under Linux? At the time, I told him that he could solve it by pattern matching. But in fact, besides, there are other methods, which are called "All roads lead to Rome". Let's take a look at them.
If you want to delete all files except *.iso and *.zip in the ~/downloads directory, you can do this in bash:
Method 1: Pattern matching method
Copy Code code as follows:
Shopt-s Extglob # Confirm open extglob option
CD ~/downloads
Rm-v! (*.iso|*.zip)
! The function of the pattern list is to match files other than the pattern list.
Method 2: Set the variable method
In bash, Globignore can be used to set the pattern-matching files to be ignored, with multiple schemas passing: delimited.
Copy Code code as follows:
CD ~/downloads
Export Globignore=*.zip:*.iso
RM-V *
Unset Globignore
Method 3:find Search Method
A friend who is familiar with find must know that the power of found is exceptionally powerful, so using it can also solve the problem.
Copy Code code as follows:
CD ~/downloads
Find. -type f-not \ (-name ' *.zip '-or-name ' *.iso ')-delete
But still want to remind everyone, RM operation is very dangerous, do not dazzle technology, if you do not trust, then can be honest one or batch delete, but also more convenient than later.