How to Delete Files Recursively in Linux
This article explains how to delete files in Linux. Then, we will elaborate on the topics below.
- Delete files recursively.
- Delete files with the same extension.
- Delete files with similar filenames.
- Delete files recursively with the same extension / similar filenames.
The sample files and directories we will use throughout the article are below.
Use the rm
Command to Delete Files in Linux
After the rm
command, type the filename(s) you want to remove.
rm file1.txt
Use the -r
Command to Delete Files Recursively in Linux
The -r
flag allows you to recursively remove directories and their contents. Type the directory name you want to delete after the rm -r
command. The use of a slash /
after the directory name is optional.
rm -r Folder2/
Use Wildcard *
to Delete Files With Similar Filenames in Linux
The asterisk *
is called wildcard, and it gives every file that starts with the specified name as a parameter to the rm
command.
We want to remove all files with the name file1
, even if the extension is different. We use a wildcard instead of specifying the extension at the end of the filename.
rm file1.*
Use Wildcard *
to Delete Files With Same Extension in Linux
This time, we want to remove all files with the same extension, even if their names are different. We use a wildcard instead of the filename then write the extension.
rm *.txt
Use the find
Command to Delete Files Recursively in Linux
We can use the find
command to find and delete files recursively with similar extensions or filenames from a directory and its sub-directories.
We can use the find
command with the -delete
.
find . -type f -name '*.txt' -delete
Alternatively, it can be used with the exec
.
find . -name '*.txt' -exec rm -r {} \;
Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.
LinkedIn