howtouselinux

6 find exec rm Command Examples to Delete Files

Table of Contents

Linux find command is a powerful tool that can be used to locate and manage files and directories based on a wide range of search criteria.

This post will cover how to delete files with find exec rm in Linux. However, some solutions in this article can be dangerous if we don’t correctly use them. We need to test this before we run it in the production environment.

What is find exec rm?

Find exec rm command is used to delete files or directories that match certain criteria. This command combines three commands together to remove any found directories or files from your system. Find exec rm is very helpful for quickly deleting files or directories based on their permissions, type, date, ownership, size, and more.

Find Syntax

When using find, we would follow the syntax below.

find [options] [path] [expression]

  • options: This is optional. We can leave this out most of the time. We can read the manual page for all the options the find command has.
  • path: This is the directory we want to search.
  • expression: This is where we place our search criteria for what we want to find whether by name, or size etc.

 

Delete Files with a specific name

Every time the find command identifies a file with the .c suffix, the rm command deletes that file.

find /directory -name “*.c” -exec rm {} \;

Delete files in multiple directories

If we want to search and delete all files with a given name in multiple directories,
we can either start the search at root folder, or if we know the directories, we can specify them.

Example:

find /path1 /path2 -name failed*.* -type f -exec rm {} \;

Delete Files Older Than x Days on Linux

find /path/to/files* -mtime +5 -exec rm {} \;

Delete Files with modifying time

To remove the files that are modified within 60 minutes, type:

find /path -mmin -60 -exec rm {} \;

Delete Large files

The first step is to find files larger than 200 MB.

The next target is to remove these files. This can be done by:

find /path -type f -size +200M -exec rm {} \;

Advanced find exec rm examples

To remove all files named a.out or *.o that are not accessed for a week and that are not mounted by using nfs, type:

find / \( -name a.out -o -name ‘*.o’ \) -atime +7 ! -fstype nfs -exec rm {} \;

Note: The number that is used within the -atime expression is +7. It is the correct entry if we want the command to act on files that are not accessed for more than a week (seven 24-hour periods).

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

If you meet any issues with Linux, record them with Loom and send the link to us here. We will reply ASAP.

Load WordPress Sites in as fast as 37ms!