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

by on February 8, 2006 · 60 comments· LAST UPDATED July 19, 2013

in , ,

I am new to Unix and Linux command line. How do I find and delete files under Linux / UNIX operating systems using shell prompt?

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.
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Requirementsfind
Estimated completion time5 minute

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
See also : Other find command usage
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 60 comments… read them below or add one }

1 Carl March 8, 2007 at 9:11 pm

Awesome, this was exactly what I needed to delete a huge amount of files when I ran out of inodes. Just doing an rm * would result in an error, but this deletes the files one at a time. Thanks

Reply

2 Rob March 29, 2007 at 3:19 pm

do any of the above commands delete .bak files recursively throughout an entire directory tree, or would I need to cd to each directory to delete its .bak files?

Reply

3 nixCraft March 30, 2007 at 3:24 am

Rob,

> would I need to cd to each directory to delete its .bak files?
No

find command will go to each sub directory. For example delete all *.bak from /data2 dir, use

find /data2 -type f -name "*.bak" -exec rm -f {} \;

Reply

4 Test September 12, 2007 at 12:37 am

Why does it require a backslash to terminate with the ;? I need to place this in an applescript under “do shell script” but it hates that backslash. Is there any way around it?

Reply

5 nixCraft September 12, 2007 at 4:53 am

A backslash is required, otherwise shell will treat ;? as part of shell command.

Reply

6 Atul February 20, 2008 at 3:33 pm

for removing directories in same manner, use command find . -type d -name “DIRNAME” -exec rm -rf {} \;

Reply

7 Atul February 20, 2008 at 3:34 pm

to recursively search and delete directories use
find . -type d -name “DIRNAME” -exec rm -rf {} \;

Reply

8 Nick March 25, 2008 at 6:33 pm

Why not use the -delete option of find?

Reply

9 Frolic August 8, 2012 at 1:43 pm

1) Maybe because it’s rather new and not widely known (yet), or possibly not yet available everywhere?
2) Because it cannot delete non-empty directories, in case you want to do that.

But generally: yes, one should also consider the “-delete” action.

Reply

10 Dr Thangpa Serto April 15, 2008 at 6:01 am

[root@localhost ieee80211-1.2.18]# make
Checking in /lib/modules/2.6.18-53.el5xen for ieee80211 components…
make -C /lib/modules/2.6.18-53.el5xen/build M=/root/Desktop/ieee80211-1.2.18 modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-53.el5-xen-i686′
CC [M] /root/Desktop/ieee80211-1.2.18/ieee80211_module.o
In file included from /root/Desktop/ieee80211-1.2.18/ieee80211_module.c:52:
/root/Desktop/ieee80211-1.2.18/compat.h:113:
Hi!

I am a linux newbie. I installed RHEL5 on a compaq Presario V3000 laptop.

Now i tried to install the wifi drivers ipw3445… but i am stuck her

error: redefinition of ‘kmemdup’
include/linux/slab.h:208: error: previous definition of ‘kmemdup’ was here
make[2]: *** [/root/Desktop/ieee80211-1.2.18/ieee80211_module.o] Error 1
make[1]: *** [_module_/root/Desktop/ieee80211-1.2.18] Error 2
make[1]: Leaving directory `/usr/src/kernels/2.6.18-53.el5-xen-i686′
make: *** [modules] Error 2
[root@localhost ieee80211-1.2.18]#

Please help

Reply

11 Robert August 24, 2010 at 1:49 am

Did you ever find a solution to this problem. If so please let me know the details because I have the exact same issue. Thank you.

Reply

12 Dani September 18, 2008 at 6:26 pm

This page has just save 3 hours of stressful, worthless work in my life. Thank you so much.

Reply

13 Anonymous November 7, 2008 at 11:27 pm

How can I remove files that contain a certain string of text? For example: if file contains any of these symbols, remove the file:

{ }
[ ]
( )

Just to name a few, but there might be others. I need a bash script to do this.

Reply

14 pfwd February 20, 2009 at 4:08 pm

Sweet thanks

Reply

15 Barack Raz February 26, 2009 at 8:16 pm

awesome…just awesome…- thank you :-) – freakin’ directory was hung…can’t ls to it for nothing or anything for that matter….but finally :-)

Reply

16 Felix February 26, 2009 at 9:33 pm

What if I wanted to remove every file from my home account except for a certain directory??
For example:
find . -name ‘.UCLA’ -prune -o -exec rm -rf {} +;

This removes everything EXCEPT my .UCLA folder, however I get a message that says:
rm: error can not remove `.’ `..’

How do I get rid of that error message?

Reply

17 madhan February 27, 2009 at 9:10 am

Thank you. It met my requiemens. IT was a timly help.

\madhan

Reply

18 Nicole March 24, 2009 at 4:27 pm

I’m trying to remove files that have a certain misc dates
Would like to do a wild card for certain parts of the file name.
Example – 03230800203805V274803.810

Would ****08***********.810 work?

Want to delete the files containing in the postions 5 and 6 for 08.

Thanks,
Nicole

Reply

19 CorkyMoo July 14, 2009 at 1:03 am

Is it not ‘ | exec ‘ and not ‘ -exec ‘ ? Either way it does not work.

Reply

20 JimmyNY July 30, 2009 at 6:01 am

Nobody has ever asked this question online it seems…

Problem: Stupid MAC (which I dont have anymore named files with these characters:
“:”
“?”
etc.. in the file names.. I could not find any file renamer that would rename these files in Windows/DOS..

So I tried FENDORA linux and I can rename the manually one by one but i have hundreds…

HELP!!!!

No RENAME or mv command works.. I trired everything i can find online..

I tried specifing the “:” like this “\:” “\x3a” etc.. and nothing.

does anyone know how to strip these retardted OS-illegal characters out of the names.. in one shot.?

I know the ren command in DOS.. but I have no clue it seems in Linux.
and no i don’t have a mac or access to one..

Thanks ahead of time, for your help.

Reply

21 Hank September 11, 2009 at 4:26 pm

This should do it:

for FILE in `find . -name ‘*\:*’`; do NEW=`echo $FILE | sed -e ‘s/:/_/’`; mv $FILE $NEW; done

Reply

22 Josh October 15, 2009 at 8:43 am

Use -delete flag with find… works much faster than -exec rm

Reply

23 durga October 22, 2009 at 11:38 pm

hey, thanks!

Reply

24 Kiran October 27, 2009 at 5:43 am

Hi,

I am trying to delete files and folders using the below command

find /opt/server/Outward/logs/ -daystart \( -type d ! \) -mtime +264 -exec rm -rf {} \;
I get the below error.
find: /opt/server/Outward/logs/2009-02-04: No such file or directory

The logs folder contains folders and sub-folders. After I execute the command i get the error message as above. What could be the possible reason and the solution.

Thanks
Kiran

Reply

25 Sailor Enlil November 17, 2009 at 1:59 am

Does find’s -delete option support or have something similar to rm’s -f flag? (i.e. force delete a file/directory even if the write permission is not set)? I need to delete files that may not be write enabled (eg r– or r-x when viewed using ls -l).

Reply

26 Roshan November 18, 2009 at 6:24 am

How to override after find command?
Note :i know find command but dont know how to combine these operations.
cat “I’m repled content” > test.zip .
ex:
1> i have to find files with name “*test*.*” and replace the content of the file with “I’m replaced content”.
2> find the file with size more than 10mb and replace the content of the file with “I’m replaced content”.

Reply

27 lupht December 3, 2009 at 7:51 am

Kiran:

Try the -ignore_readdir_race option

Reply

28 Tristan April 3, 2010 at 4:58 pm

Very nice find. Had a bunch of music I copied over from my Mac that had Ableton files in them which weren’t needed on my laptop.

Quick way of getting rid of them.

Thanks a bunch.

Reply

29 Jeremy September 26, 2010 at 5:15 am

Fantastic tips. These helped me create some commands to add to my ~/.bash_logout file to perform file/directory cleanup on logout. Cheers!

Reply

30 liveD September 30, 2010 at 7:29 am

find . -type f -name “FILE-TO-FIND” -delete;

Reply

31 Chethan October 15, 2010 at 6:14 am

#include

int main()
{
execl(“/bin/rm”, “rm”, “-f”, “/home/cc/rr* “, (char*)0);
printf(“end”);
return 0;
}

In the above program, I want to delete all file /home/cc/rr*. With above program it is not working, I mean it is not deleting. Please help.

Reply

32 TheRiley November 10, 2010 at 10:14 pm

this culls directories older than 10 days:

find /somePath -type d -name ‘someNamePrefix*’ -mtime +10 -print | xargs rm -rf ;

Reply

33 Bruce Jenkins March 18, 2011 at 1:24 pm

Thanks for the code Riley! I have been looking for something like this.

Reply

34 Badtz March 22, 2011 at 3:42 pm

-delete will also work in a directory with say… hundreds of thousands of files, -exec rm -rf will crash.

Reply

35 E1Suave March 14, 2012 at 6:54 pm

I have never seen the exec rm -rf crash and I run it to scan over 150,000 files throughout the entire OS.

Reply

36 Badtz March 22, 2011 at 3:47 pm

For instance

/bin/rm: Argument list too long
-bash-3.2$ ls -l | wc -l
161995
-bash-3.2$ find . -delete
-bash-3.2$

Reply

37 surreyian April 28, 2011 at 4:30 pm

i tried to use the command to find and delete files

find . -name “find name” -exec rm {}\

but the return message is missing argument to ‘-exec’

what have I done wrong?

Reply

38 nixCraft April 28, 2011 at 10:47 pm

Add semicolon (;) to command:
find . -name “find name” -exec rm {}\ ;

Reply

39 surreyian May 4, 2011 at 8:25 am

thanks

Reply

40 rangga June 28, 2011 at 6:24 am

can we combine locate with rm ?

thanks

Reply

41 beli June 29, 2011 at 12:04 pm

Thanks!

Reply

42 Basil July 6, 2011 at 3:17 pm

How can check and redirect to a single file with the file names that contains the certain string of text? For example:

If my files abc.txt, aaa.txt and bbb.txt where both aaa and bbb contains ERROR, and abc not. I need to point out the names aaa.txt and bbb.txt to another file ccc.txt…

Just to name a few, but there might be others. I need a bash script to do this.
Am searching for a solution from a week…:(

Reply

43 Sashidhar December 10, 2013 at 2:43 pm

Sorry for the late reply. I only nw saw this and also saw there was no response for this.

grep -lir "Text to search" / (will search all files in all filesystems and report the filenames).

Output that to an external file as you desire.

grep -lir "Text to search" / >> myfile_list_to_delete.log
grep -lir "Text to search" /home >> myfile_list_to_delete.log

The above will find only in the /home folder.

Reply

44 Question August 9, 2011 at 11:34 pm

is there supposed to be a space before -exec in the example?
find . -type f -name “FILE-TO-FIND” -exec rm -f {} \;

Reply

45 Ankit August 25, 2011 at 8:48 am

Hi All,

I want to find and delete some files from a single directory only, i mean i dnt want the find command to search any other sub directories how do i do tht???

Reply

46 vijay October 11, 2011 at 4:39 am

how to delete only c & java programs in red hat linux….

Reply

47 Asghar Ali October 30, 2011 at 1:11 pm

Thanks Dude! I really need it.

Reply

48 Asghar Ali March 31, 2012 at 7:33 pm

Thank you so much! it really helped..

Reply

49 Mykhailo June 24, 2012 at 9:35 am

Hi,

Can someone explain me strange behavior of deleting folder via find -exec.
So I have folder ‘test’.
When I’m executing such command:

find ‘/Volumes/Storage/Dropbox/Backups’ -type d -name ‘test’ -exec rm -rf {} \;

It says: find: /Volumes/Storage/Dropbox/Backups/test: No such file or directory

BUT deletes it successfully.

Why does it happen? What am I doing wrong? I need to avoid this error message because it causes exception in my script.

Reply

50 Captain Mac June 26, 2012 at 11:28 pm

try
“\\; ” instead of “\; “. double backslash is actually represent one backslash in a C-like ASCII string
do shell script “find /data2 -type f -name “*.bak” -exec rm -f {} \\; ”

Test September 12, 2007 at 12:37 am

Why does it require a backslash to terminate with the ;? I need to place this in an applescript under “do shell script” but it hates that backslash. Is there any way around it?

Reply

51 Mykhailo July 7, 2012 at 12:48 pm

Captain Mac June 26, 2012 at 11:28 pm
try
“\\; ” instead of “\; “. double backslash is actually represent one backslash in a C-like ASCII string
do shell script “find /data2 -type f -name “*.bak” -exec rm -f {} \\; ”

Double slashes produces incorrect syntax for bash saying:
“find: -exec: no terminating “;” or “+””

For applescript it’s requires escaping one slash with double but it doesn’t help and produces the error above.

Still don’t have solution :(

Reply

52 Captain Mac July 9, 2012 at 6:33 am

Can you write exact of your applescript to the site? Since It worked on my mac to clean Picasa Originals directories…

Other option remove single quotes and if necessary “;” from your script.

Worst case scenario, try exception handling on the script without any action, if it works OK but throws exceptions only.

Reply

53 Mykhailo July 19, 2012 at 5:14 pm

Here is my applescript:

on run {input, parameters}
do shell script “find /Users/moleksyuk/Temp -type d -name ‘test’ -exec rm -rf {} \\;”
return input
end run

Script with one slash:

do shell script “find /Users/moleksyuk/Temp -type d -name ‘test’ -exec rm -rf {} \;”

Or without semicolon

do shell script “find /Users/moleksyuk/Temp -type d -name ‘test’ -exec rm -rf {} \\”

are not valid for Automator.

Screenshot

Reply

54 Mykhailo July 19, 2012 at 5:19 pm

Here is my applescript:

on run {input, parameters}
do shell script “find /Users/moleksyuk/Temp -type d -name ‘test’ -exec rm -rf {} \\;”
return input
end run

Other combinations (with one slash or without semicolon) are not valid for Automator.

Error screenshot here – http://goo.gl/DE7UB

Reply

55 Sanjeev August 22, 2012 at 12:43 pm

Thanks mate – worked to take out .htaccess files splattered over my directories by commitse.

Reply

56 Neeraj October 9, 2012 at 6:25 am

Hi i have a task to find the specific folder by name. I did that by using “find . -type d “example” ” now i have to find the folders of a specific user from the list of folder given by find command above.

ex : if i have folder example-created by A, example-by B and example-by C
then the above command will give
example-byA
example-byB
example-byC

now after this i just want to access or find the folders created by B user

it should provide only example-byB user

Can any one show some light on this and help me out

Thanks

Reply

57 Vitalij October 17, 2012 at 7:24 pm

Hi! I have a problem with this commands…. I try to find file and hen delete it however i cant =\
with this command i get the right o/p but i cant make to delete this file:
ls -aR /media/DATA/downloads/music | grep -iF “04 Edith Piaf – Platinum Collection [CD 1] – Mon Dieu”
the idea is to delete file passing only one parameter without changing it -> name of file
when i try this:
rm `ls -aR /media/DATA/downloads/music | grep -iF “04 Edith Piaf – Platinum Collection [CD 1] – Mon Dieu”` i get errors where each part of string(file name) is separated. I tried with find to, any nothing, so i hope someone an help me ;)

Reply

58 Niki July 19, 2013 at 8:59 am

Very bad article !!!
What means -type ???
What means -name ???
Just a command without any explanation!

Reply

59 komischer vogel May 6, 2014 at 11:23 pm

hi,

im using find -f folder/* -mmin +120 -delete

to delete all files within older than 2 hours and using cron to exec the script hourly, but its gets me an error mail all time when there is no file to delete.

how can i check, that files exist to first?

Reply

60 komischer vogel May 7, 2014 at 1:15 pm

ok found it out myself:

#!/bin/bash

DIR=”/folder/path/”
if [ "$(ls -A $DIR)" ]; then
find /folder/path/* -mmin +120 -delete
else
exit 0
fi

Reply

Leave a Comment

Tagged as: , , , , , , , , , , ,

Previous Faq:

Next Faq: