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:

$ rm <filename1> <filename2> ... <filenameN>

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:

$ rm *test*

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 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:

$ rm *.gif
Delete Files with Particular Extension
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:

$ rm -r <file/folder1> <file/folder2> ... <file/folderN>

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:

$ find . -name "*.png"
Search Files Recursively with Extension
Search Files Recursively with Extension

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

$ find . -name "*.png" | xargs rm 
Delete Files Recursively with Extension
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.

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.

Got something to say? Join the discussion.