Linux remove all files with extension

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

Читайте также:  Как скинуть пароль для windows

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 Remove Files with Specific Extension in Linux

To remove files with a specific extension, we use the ‘rm‘ (Remove) command, which is a basic command-line utility for removing system files, directories, symbolic links, device nodes, pipes, and sockets in Linux.

The command is quite simple to use and the basic syntax is:

Here, ‘filename1‘, ‘filename2‘, etc. are the names of the files including full path. If the files are in the same directory then, as you might already know, there is no need to write down full paths.

We can also use wildcard expressions to specify files that have similar or incremental names or to specify files with a specific file extension.

Remove Files in Linux Using Substring

For example, to remove all files contain the substring ‘test‘, we can run:

Here, the ‘*’ implies ‘any string‘. Hence the pattern ‘*test*’ considers all files with names containing the substring ‘test‘.

Remove File Using SubString of Filename

Remove Files with File Extension in Linux

Let’s take another example. We will try to delete all GIF files from the folder using the following:

Delete Files with Particular Extension

However, this syntax works only for files. Using the argument ‘-r’ we can delete both files as well as folders:

Note that this will delete the folder recursively in its entirety, i.e., it will delete the entire folder structure beneath it; the subfolders and all the files. Hence, there is no way to delete specific files with a pattern of filenames, or files with a specific extension recursively. Every time the entire folder structure is deleted.

Remove Files Recursively with File Extension in Linux

To achieve this, we can make use of the find command and pipe its output to ‘rm’. The find command is simply used to search for files recursively based on parameters like the filename, extension, size, etc.

For example, to search recursively for files with extension “.png” , we run the following:

Search Files Recursively with Extension

Now, we simply pipe this output to ‘rm’ in the following way:

Delete Files Recursively with Extension

The ‘xargs’ command is simply used to pass the output of ‘find’ to ‘rm‘ as arguments. In this way, we have recursively deleted files of the extension PNG from the whole folder structure.

Читайте также:  Opendiag для windows полная версия
Conclusion

In this article, we learned about the ‘rm‘ command, how to delete files and folders using it, and how to delta files recursively with specific extensions.

If you have any questions or feedback, let us know in the comments below.

Источник

How can I recursively delete all files of a specific extension in the current directory?

How do I safely delete all files with a specific extension (e.g. .bak ) from current directory and all subfolders using one command-line? Simply, I’m afraid to use rm since I used it wrong once and now I need advice.

8 Answers 8

You don’t even need to use rm in this case if you are afraid. Use find :

But use it with precaution. Run first:

to see exactly which files you will remove.

Also, make sure that -delete is the last argument in your command. If you put it before the -name *.bak argument , it will delete everything.

See man find and man rm for more info and see also this related question on SE:

First run the command shopt -s globstar . You can run that on the command line, and it’ll have effect only in that shell window. You can put it in your .bashrc , and then all newly started shells will pick it up. The effect of that command is to make **/ match files in the current directory and its subdirectories recursively (by default, **/ means the same thing as */ : only in the immediate subdirectories). Then:

(or gvfs-trash **/*.bak or what have you).

Deleting files is for me not something you should use rm for. Here is an alternative:

As Flimm states in the comments:

The package trash-cli does the same thing as gvfs-trash without the dependency on gvfs.

You don’t need to make an alias for this, because the trash-cli package provides a command trash , which does what we want.

As Eliah Kagan makes clear in extensive comments, you can also make this recursive using find . In that case you can’t use an alias, so the commands below assume you have installed trash-cli . I summarise Eliah’s comments:

This command finds and displays all .bak files and symlinks anywhere in the current directory or its subdirectories or below.

To delete them, append an -exec with the trash command:

-xtype f selects files and symlinks to files, but not folders. To delete .bak folders too, remove that part, and use -execdir , which avoids cannot trash non-existent errors for .bak files inside .bak directories:

Источник

How To Delete File In Linux?

Deleting files in Linux can be sometimes tricky. We have a tool named rm which is the shortcut for the word remove. In this tutorial, we will look at how to remove or delete a file in Linux with different examples and ways.

rm Command Syntax

rm command syntax is the same as the most the Linux command. We can provide options before specifying the file and directories we cant to operate or delete.

  • OPTINS states the behavior of the rm command as we will see below in detail.
  • FILENAME is the file or directory name we want to delete or operate.

rm Command Help

rm command help information can be printed to the console with the —help command which is like below. Help information will provide some popular options and usages.

Delete Single File with rm Command

We will start with simple steps just deleting a single file. We will just specify the file name we want to delete. In order to remove the file successfully, we should have privileges to modify a file. For example, if we try to remove the file owned by root with a regular user we will get an error and would not delete the file. In this example, we will delete the file named foo.txt

Читайте также:  Apk как установить windows mobile

Delete Multiple Files with rm Command

We have the ability to delete multiple files in a single rm command. We will just put file names we want to delete by separating them with space. In this example, we will delete file names foo.txt and bar.txt but we can add more if we need it.

Delete Files According To Their Extensions/Types with rm Command

Linux bahs provides the glob or asterisk in order to specify the files with a specific name or extension. We can use glob * in order to specify a specific extension like *.txt , *.pdf , *.tmp etc. We can use this extension or name specification in order to delete specific files. In this example, we will delete all *.deb extensions.

We can also specify names like deleting all files which name starts with pof like below.

Delete Files Recursively

rm command provides the ability to delete or remove files recursively. Recursive removal will check subdirectories for files to remove with the directories. We will remove the directory name ndiff with all sub-directories and files in this example. We will use -R option for the recursive operation.

Delete File with Prompt Before Every Removal

While removing files and directories we may need approval for each file to delete. In this case, we can use -i option which will prompt to accept or deny deletion of the given file.

While deleting files and directories we may want to see details of the removal operation. rm command provides a verbose option which will list information about each deletion of file or directory. We will use -v option for this.

Delete empty Directories or Folders with rmdir Command

In some cases, we need to delete empty folders. rm without options will not work in this case as we can see this in the following screenshot. We case use rmdir command to remove an empty directory or folder.

Read File Names From Text File For Delete or Removal

Another interesting use case for rm command is providing file or directory names from a list like a text file. We will use xargs command to-read the list and redirect to the rm command.

Delete File Names Starts with Dash —

Another interesting case is dash or — problem where file or directory names starting with dash . As we know Linux commands options are specified with dash . So how can rm recognize file name from option? We will use — or double dash were to specify the file or directory name start. For example we have a file named -file.txt and we want to remove. We will use the following command. As we can see the file name is specified after double dash. Options are specified before the double dash.

Delete Files By Reading Their Names From A File/List

In some cases, we may need to read a list that contains the file names we want to delete. This is generally a simple text file where each file name with their path is specified line by line. We can use xargs command to redirect the list contents to the rm command which will delete them one by one. In this example, we will read the list file names file-list.txt .

Delete Files By Finding them with find Command

find is a very useful command which is used to find files and folders. find command also provides some options like running commands on the search results. We can also remove or delete files found by the find command. In this example, we will delete files that are older than 3 days.

Источник

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