I am new to Unix and Linux command line. How do I find and delete all files (say all ‘*.bak’) under Linux / UNIX-like operating systems using a shell prompt?

Sometimes it is necessary to find out all files and remove them in a single go. However, the rm command does not support search criteria. For example, find all “*.bak” files and delete them. For such necessities, you need to use the find command to search for files in a directory and remove them on the fly. You can combine find and rm command together. This page explains how to find and remove files with one command on fly.

ADVERTISEMENTS

Find And Remove Files With One Command On Fly

The basic find command syntax is as follows:

find dir-name criteria action

Where,

  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.

You want to remove multiple files such as ‘.jpg’ or ‘.sh’ with one command find, try:

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

OR

find /dir/to/search/ -type f -name "FILE-TO-FIND-Regex" -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. Where, options are as follows:

  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.
  4. -type d : Only match dirs and do not include files names.

Modern version of find command has -delete option too. Instead of using the -exec rm -rf {} ;, use the -delete to delete all matched files. We can also explicitly pass the -depth option to the find to process each directory’s contents before the directory itself. It is also possible to use the -maxdepth option to control descend at most levels of directories below the starting-points. For example, -maxdepth 0 means only apply the tests and actions to the starting-points themselves. Similary, we can pass the -mindepth to the find. It means do not apply any tests or actions at levels less than levels (a non-negative integer). For exampe, -mindepth 1 means process all files except the starting-points. So here is a simplied syntax:

find /dir/to/search/ -type f -name "FILES-TO-FIND" -delete

find /dir/to/search/ -type f -name "FILES-TO-FIND" -depth -delete

find /dir/to/search/ -maxdepth 2 -type f -name "FILES-TO-FIND" -depth -delete

#linux

Find and Remove Files With One Linux Command On Fly - nixCraft
1.70 GEEK