A colleague of mine once asked me a question: how do I delete all files in the directory except for some files under Linux? At the time, I told him that it could be solved by pattern matching method. But in fact, in addition, there are other methods, is the so-called "all Roads to Rome." Let's take a look at each.
Assuming you want to delete all files except *.iso and *.zip in the ~/downloads directory, you can do this in bash as follows:
Method 1: Pattern matching method
Shopt-s Extglob # Confirm to turn on the EXTGLOB option CD ~/downloadsrm-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 file to ignore, with multiple modes separated by:
CD ~/downloadsexport globignore=*.zip:*.isorm-v *unset globignore
Method 3:find Search Method
A friend familiar with find must know that the power of find is unusually powerful, so using it can also solve this problem.
CD ~/downloadsfind. -type f-not \ (-name ' *.zip '-or-name ' *.iso ' \)-delete
But still want to remind everyone, RM operation is very dangerous, do not dazzle skill, if you do not rest assured, then can first honest one or batch delete, also be more convenient than afterwards.
How do I delete "All files except some files" in Bash?