Linux all files except

3 Ways to Delete All Files in a Directory Except One or Few Files with Extensions

Sometimes you get into a situation where you need to delete all files in a directory or simply cleanup a directory by removing all files except files of a given type (ending with a particular extension).

In this article, we will show you how to delete files in a directory except certain file extensions or types using rm, find and globignore commands.

Before we move any further, let us start by briefly having a look at one important concept in Linux – filename pattern matching, which will enable us to deal with our issue at hand.

In Linux, a shell pattern is a string that consists of the following special characters, which are referred to as wildcards or metacharacters:

  1. * – matches zero or more characters
  2. ? – matches any single character
  3. [seq] – matches any character in seq
  4. [!seq] – matches any character not in seq

There are three possible methods we shall explore here, and these include:

Delete Files Using Extended Pattern Matching Operators

The different extended pattern matching operators are listed below, where pattern-list is a list containing one or more filenames, separated using the | character:

  1. *(pattern-list) – matches zero or more occurrences of the specified patterns
  2. ?(pattern-list) – matches zero or one occurrence of the specified patterns
  3. +(pattern-list) – matches one or more occurrences of the specified patterns
  4. @(pattern-list) – matches one of the specified patterns
  5. !(pattern-list) – matches anything except one of the given patterns

To use them, enable the extglob shell option as follows:

1. To delete all files in a directory except filename, type the command below:

Delete All Files Except One File in Linux

2. To delete all files with the exception of filename1 and filename2:

Delete All Files Except Few Files in Linux

3. The example below shows how to remove all files other than all .zip files interactively:

Читайте также:  Какие проблемы могут возникнуть при установке windows 10

Delete All Files Except Zip Files in Linux

4. Next, you can delete all files in a directory apart from all .zip and .odt files as follows, while displaying what is being done:

Delete All Files Except Certain File Extensions

Once you have all the required commands, turn off the extglob shell option like so:

Delete Files Using Linux find Command

Under this method, we can use find command exclusively with appropriate options or in conjunction with xargs command by employing a pipeline as in the forms below:

5. The following command will delete all files apart from .gz files in the current directory:

Command find – Remove All Files Except .gz Files

6. Using a pipeline and xargs, you can modify the case above as follows:

Remove Files Using find and xargs Commands

7. Let us look at one additional example, the command below will wipe out all files excluding .gz , .odt , and .jpg files in the current directory:

Remove All Files Except File Extensions

Delete Files Using Bash GLOBIGNORE Variable

This last approach however, only works with bash. Here, the GLOBIGNORE variable stores a colon-separated pattern-list (filenames) to be ignored by pathname expansion.

To employ this method, move into the directory that you wish to clean up, then set the GLOBIGNORE variable as follows:

In this instance, all files other than .odt , .iso , and .txt files with be removed from the current directory.

Now run the command to clean up the directory:

Afterwards, turn off GLOBIGNORE variable:

Delete Files Using Bash GLOBIGNORE Variable

Note: To understand the meaning of the flags employed in the commands above, refer to the man pages of each command we have used in the various illustrations.

Thats all! If you have any other command line techniques in mind for the same purpose, do not forget to share with us via our feedback section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How to find files except given name?

There is a directory containing the following files:

I need to find and delete all of the files that in the format of *.7z except _*.7z

How I can do it?

4 Answers 4

Another approach is to use an additional, negated primary with find :

The simple regex in the other answers is better for your use case, but this demonstrates a more general approach using the ! operator available to find .

Читайте также:  Linux check network traffic

In regular expressions, the ^ operator means «any character except for». Thus [^_] means «any character except for _». E.g.:

So, if your intention is to exclude files starting with _ , your full command line would be:

If you’d like to exclude any occerance of _ , you can use the and and not operators of find , like:

A quick way given you have bash 4.2.25, is to simply use bash pattern matching to remove all .7z, but the ones having _.7z, like this:

Not the answer you’re looking for? Browse other questions tagged linux bash find or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Delete all files except the newest 3 in bash script

Question: How do you delete all files in a directory except the newest 3?

Finding the newest 3 files is simple:

But I need to find all files except the newest 3 files. How do I do that, and how do I delete these files in the same line without making an unnecessary for loop for that?

I’m using Debian Wheezy and bash scripts for this.

11 Answers 11

This will list all files except the newest three:

This will delete those files:

This will also list dotfiles:

and delete with dotfiles:

But beware: parsing ls can be dangerous when the filenames contain funny characters like newlines or spaces. If you are certain that your filenames do not contain funny characters then parsing ls is quite safe, even more so if it is a one time only script.

If you are developing a script for repeated use then you should most certainly not parse the output of ls and use the methods described here: http://mywiki.wooledge.org/ParsingLs

Solution without problems with «ls» (strange named files)

This is a combination of ceving’s and anubhava’s answer. Both solutions are not working for me. Because I was looking for a script that should run every day for backing up files in an archive, I wanted to avoid problems with ls (someone could have saved some funny named file in my backup folder). So I modified the mentioned solutions to fit my needs.

My solution deletes all files, except the three newest files.

find lists all files (not directories) in current folder. They are printed out with timestamps.
sort sorts the lines based on timestamp (oldest on top).
head prints out the top lines, up to the last 3 lines.
cut removes the timestamps.
xargs runs rm for every selected file.

Читайте также:  Windows не загружается не был найден файл

For you to verify my solution:

This creates 5 files with different timestamps in the current folder. Run this script first and then the code for deleting old files.

Источник

BASH copy all files except one

I would like to copy all files out of a dir except for one named Default.png. It seems that there are a number of ways to do this. What seems the most effective to you?

7 Answers 7

Should be as follows:

If copying to a folder nested in the current folder (called example in the case below) you need to omit that directory also:

rsync has been my cp/scp replacement for a long time:

Simple, if src/ only contains files:

If src/ has sub-directories, this omits them, but does copy files inside of them:

If src/ has sub-directories, this does not recurse into them:

unless the files are big. Otherwise use e.g.

use the shell’s expansion parameter with regex

Everything will be copied except for the not_to_copy_file

— if something is wrong with this. please Specify !

Not the answer you’re looking for? Browse other questions tagged bash scripting copy or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to delete all files in a directory except some?

I need to delete all files in a directory, but exclude some of them. For example, in a directory with the files a b c . z , I need to delete all except for u and p . Is there an easy way to do this?

17 Answers 17

What I do in those cases is to type

Then I press Ctrl + X , * to expand * into all visible file names.

Then I can just remove the two files I like to keep from the list and finally execute the command line.

To rm all but u,p in bash just type:

This requires the following option to be set:

You can use find

  • ! negates the next expression
  • -name specifies a filename
  • -maxdepth 1 will make find process the specified directory only ( find by default traverses directories)
  • -type f will process only files (and not for example directories)
  • -delete will delete the files

You can then tune the conditions looking at the man page of find

Update

    Keep in mind that the order of the elements of the expressions is significant (see the documentation)

Test your command first by using -print instead of -delete

Источник

Оцените статью