How do I delete "All files except some files" in Bash?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.