Linux: Using the ‘find’ Command to Remove All Instances of a File Within a Directory Tree

This article describes how to find all instances of a file (or files matching a pattern) in a directory tree and then perform an action on them, e.g. deleting them.

There are many ways to skin this particular cat and this is one of them!

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" | xargs rm -rf {} \;

OR

find . -type f -name "FILE-TO-FIND" | xargs rm -f {} \;

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

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

 

Example:

To delete all the readme.html and readme.txt files in a wordpress installation located in the /var/www directory you could first of all list them to make sure you’re not going to delete something you want to keep:

find /var/www/ -name readme.* | xargs ls -la {} \;

And then delete them:

find /var/www/ -name readme.* | xargs rm -f {} \;

Leave a ReplyCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version
%%footer%%