Linux delete all 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:

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.

Источник

Remove all files except some from a directory

When using sudo rm -r , how can I delete all files, with the exception of the following:

19 Answers 19

If you don’t specify -type f find will also list directories, which you may not want.

Or a more general solution using the very useful combination find | xargs :

for example, delete all non txt-files in the current directory:

The print0 and -0 combination is needed if there are spaces in any of the filenames that should be deleted.

The extglob (Extended Pattern Matching) needs to be enabled in BASH (if it’s not enabled):

find . | grep -v «excluded files criteria» | xargs rm

This will list all files in current directory, then list all those that don’t match your criteria (beware of it matching directory names) and then remove them.

Update: based on your edit, if you really want to delete everything from current directory except files you listed, this can be used:

It will create a backup directory /tmp_backup (you’ve got root privileges, right?), move files you listed to that directory, delete recursively everything in current directory (you know that you’re in the right directory, do you?), move back to current directory everything from /tmp_backup and finally, delete /tmp_backup .

I choose the backup directory to be in root, because if you’re trying to delete everything recursively from root, your system will have big problems.

Surely there are more elegant ways to do this, but this one is pretty straightforward.

Читайте также:  Practical reverse engineering x86 x64 arm windows kernel reversing tools and obfuscation

Источник

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

Источник

Using find — Deleting all files/directories (in Linux ) except any one

If we want to delete all files and directories we use, rm -rf * .

But what if i want all files and directories be deleted at a shot, except one particular file?

Is there any command for that? rm -rf * gives the ease of deletion at one shot, but deletes even my favourite file/directory.

Thanks in advance

11 Answers 11

find can be a very good friend:

find * -maxdepth 0 : select everything selected by * without descending into any directories

-name ‘b’ -prune : do not bother ( -prune ) with anything that matches the condition -name ‘b’

-o -exec rm -rf ‘<>‘ ‘;’ : call rm -rf for everything else

By the way, another, possibly simpler, way would be to move or rename your favourite directory so that it is not in the way:

Short answer

Details:

The thought process for the above command is :

  • List all files (ls)
  • Ignore one file named «z.txt» (grep -v «z.txt»)
  • Delete the listed files other than z.txt (xargs rm)

Create 5 files as shown below:

List all files except z.txt

We can now delete(rm) the listed files by using the xargs utility :

You can type it right in the command-line or use this keystroke in the script

P.S. I suggest -i switch for rm to prevent delition of important data.

P.P.S You can write the small script based on this solution and place it to the /usr/bin (e.g. /usr/bin/rmf ). Now you can use it as and ordinary app:

The script looks like (just a sketch):

At least in zsh

could be an option, if you only want to preserve one single file.

If it’s just one file, one simple way is to move that file to /tmp or something, rm -Rf the directory and then move it back. You could alias this as a simple command.

The other option is to do a find and then grep out what you don’t want (using -v or directly using one of find s predicates) and then rm ing the remaining files.

Читайте также:  Ошибка при запуске приложения 0xc0000142 как исправить windows 10 ворде

For a single file, I’d do the former. For anything more, I’d write something custom similar to what thkala said.

In bash you have the !() glob operator, which inverts the matched pattern. So to delete everything except the file my_file_name.txt , try this:

I don’t know of such a program, but I have wanted it in the past for some times. The basic syntax would be:

The program I have in mind has three modes:

  • exact matching (with the option -e )
  • glob matching (default, like shown in the above example)
  • regex matching (with the option -r )

It takes the patterns to be excluded from the command line, followed by the separator — , followed by the file names. Alternatively, the file names might be read from stdin (if the option -s is given), each on a line.

Such a program should not be hard to write, in either C or the Shell Command Language. And it makes a good excercise for learning the Unix basics. When you do it as a shell program, you have to watch for filenames containing whitespace and other special characters, of course.

Источник

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.

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.

Источник

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