3 Methods for removing all files outside some files in the shell _linux shell

Source: Internet
Author: User

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.

Related Article

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.