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*
'*' implies ‘any string‘. Hence the pattern
'*test*' considers all files with names containing the substring ‘test‘.
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
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"
Now, we simply pipe this output to ‘rm’ in the following way:
$ find . -name "*.png" | xargs rm
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.
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.
2 thoughts on “How to Remove Files with Specific Extension in Linux”
I run the command
"rm *(1)*"as I want to delete files from the directory that contain
(1)in the filename, but every file gets deleted.
That’s because the filename contains the brackets
(1), to delete the filename with brackets check this article at: https://unix.stackexchange.com/questions/98222/deleting-all-files-that-begins-with-parenthesis