fbpx

Linux/Unix: Find And Remove Files With One Command On Fly

Some time it is necessary to find out files and remove them. However, rm command does not support search criteria. You need to use the find command to search for files in a directory and remove them on fly. You can combine find and rm command together.

Linux or UNIX – Find and remove file syntax

The basic find command syntax is:

find dir-name criteria action

  1. dir-name : – Defines the working directory such as look into /tmp/
  2. criteria : Use to select files such as “*.sh”
  3. action : The find action (what-to-do on file) such as delete the file.

To remove multiple files such as *.jpg or *.sh with one command find, use:

find . -name “FILE-TO-FIND” -exec rm -rf {} \;

OR

find . -type f -name “FILE-TO-FIND” -exec rm -f {} \;

The only difference between above two syntax is that the first command remove directories as well where second command only removes files. Options:

  1. -name “FILE-TO-FIND” : File pattern.
  2. -exec rm -rf {} \; : Delete all files matched by file pattern.
  3. -type f : Only match files and do not include directory names.

Examples of find command

WARNING! These examples may crash your computer if executed. Before removing file makes sure, you have backup of all-important files. Do not use rm command as root user it can do critical damage to the system.

Find all files having .bak (*.bak) extension in the current directory and remove them:
$ find . -type f -name "*.bak" -exec rm -f {} \;

Find all core files in the / (root) directory and remove them (be careful with this command):
# find / -name core -exec rm -f {} \;

Find all *.bak files in the current directory and removes them with confirmation from user:
$ find . -type f -name "*.bak" -exec rm -i {} \;
Sample outputs:

rm: remove regular empty file `./data0002.bak'? y
rm: remove regular empty file `./d234234234fsdf.bak'? y
rm: remove regular empty file `./backup-20-10-2005.bak'? n

Share:

Facebook
Twitter
Pinterest
LinkedIn
GMS, We Provide Solutions

GMS, We Provide Solutions

We are focused on delivering the best to our clients and visitors.

Most Popular

Social Media

Get The Latest Updates

Subscribe To Our Deals Newsletter

No spam, notifications only about new products, updates and Deals.