How to Delete Files Recursively in Linux

Yahya Irmak Feb 02, 2024
How to Delete Files Recursively in Linux

This article explains how to delete files in Linux. Then, we will elaborate on the topics below.

  1. Delete files recursively.
  2. Delete files with the same extension.
  3. Delete files with similar filenames.
  4. Delete files recursively with the same extension / similar filenames.

The sample files and directories we will use throughout the article are below.

Files and directory structure

Use the rm Command to Delete Files in Linux

After the rm command, type the filename(s) you want to remove.

rm file1.txt

Delete Files With the rm

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 the -r for delete recursively

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 for Similar Filenames

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 Wildcard for Same Extension

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

Use find with delete

Alternatively, it can be used with the exec.

find . -name '*.txt' -exec rm -r {} \;

Use find with exec

Author: Yahya Irmak
Yahya Irmak avatar Yahya Irmak avatar

Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.

LinkedIn

Related Article - Linux File