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

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.
Tutorial details
Difficulty level Easy
Root privileges No
Requirements find
Est. reading time 5 minute

Find And Remove Files With One Command On Fly

The basic find command syntax is as follows:
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.

You want to remove multiple files such as ‘*.jpg’ or ‘*.sh’ with one command find, try:
find . -name "FILE-TO-FIND" -exec rm -rf {} \;
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

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 . -type f -name "*.bak" -delete
Find all core files in the / (root) directory and remove them (be careful with this command):
# find / -name core -exec rm -f {} \;
### OR ###
# find / -name core -delete

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

The -delete always works better because it doesn’t have to spawn an external process such as rm for every matched file. However, the -delete option may not available on all find versions. Hence, we can use the xargs command as follows too:
find . -type f -name "*.err" -print0 | xargs -I {} -0 rm -v "{}"
Linux Unix macOS Find And Remove Files using a single command
Where the find command option is as follows:

  • -print0 – Force find command to print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs.

And the xargs command options are as follows:

  • -I {} : Replace occurrences of {} in the initial-arguments with names read from standard input. We pass {} as arg to the rm command.
  • -0 : Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode.
  • rm -v "{}" : Run rm command on matched files.


  • For detailed information on find command please see finding/locating files with find command part # 1, Part # 2.
  • Man pages : rm(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 72 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
72 comments… add one
  • Carl Mar 8, 2007 @ 21:11

    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

  • Rob Mar 29, 2007 @ 15:19

    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?

  • 🐧 nixCraft Mar 30, 2007 @ 3:24


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

    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 {} \;

  • Test Sep 12, 2007 @ 0:37

    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?

  • 🐧 nixCraft Sep 12, 2007 @ 4:53

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

  • Atul Feb 20, 2008 @ 15:33

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

  • Atul Feb 20, 2008 @ 15:34

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

  • Nick Mar 25, 2008 @ 18:33

    Why not use the -delete option of find?

    • Frolic Aug 8, 2012 @ 13:43

      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.

  • Dr Thangpa Serto Apr 15, 2008 @ 6:01

    [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:

    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

    • Robert Aug 24, 2010 @ 1:49

      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.

  • Dani Sep 18, 2008 @ 18:26

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

  • Anonymous Nov 7, 2008 @ 23:27

    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.

  • pfwd Feb 20, 2009 @ 16:08

    Sweet thanks

  • Barack Raz Feb 26, 2009 @ 20:16

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

  • Felix Feb 26, 2009 @ 21:33

    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?

  • madhan Feb 27, 2009 @ 9:10

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


  • Nicole Mar 24, 2009 @ 16:27

    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.


  • CorkyMoo Jul 14, 2009 @ 1:03

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

  • JimmyNY Jul 30, 2009 @ 6:01

    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…


    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.

  • Hank Sep 11, 2009 @ 16:26

    This should do it:

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

  • Josh Oct 15, 2009 @ 8:43

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

  • durga Oct 22, 2009 @ 23:38

    hey, thanks!

  • Kiran Oct 27, 2009 @ 5:43


    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.


  • Sailor Enlil Nov 17, 2009 @ 1:59

    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).

  • Roshan Nov 18, 2009 @ 6:24

    How to override after find command?
    Note :i know find command but dont know how to combine these operations.
    cat “I’m repled content” > .
    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”.

  • lupht Dec 3, 2009 @ 7:51


    Try the -ignore_readdir_race option

  • Tristan Apr 3, 2010 @ 16:58

    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.

  • Jeremy Sep 26, 2010 @ 5:15

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

  • liveD Sep 30, 2010 @ 7:29

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

  • Chethan Oct 15, 2010 @ 6:14


    int main()
    execl(“/bin/rm”, “rm”, “-f”, “/home/cc/rr* “, (char*)0);
    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.

  • TheRiley Nov 10, 2010 @ 22:14

    this culls directories older than 10 days:

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

    • Bruce Jenkins Mar 18, 2011 @ 13:24

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

  • Badtz Mar 22, 2011 @ 15:42

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

    • E1Suave Mar 14, 2012 @ 18:54

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

  • Badtz Mar 22, 2011 @ 15:47

    For instance

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

  • surreyian Apr 28, 2011 @ 16:30

    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?

    • 🐧 nixCraft Apr 28, 2011 @ 22:47

      Add semicolon (;) to command:
      find . -name "file-names-regex" -exec rm {}\ ;

      • surreyian May 4, 2011 @ 8:25


  • rangga Jun 28, 2011 @ 6:24

    can we combine locate with rm ?


  • beli Jun 29, 2011 @ 12:04


  • Basil Jul 6, 2011 @ 15:17

    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…:(

    • Sashidhar Dec 10, 2013 @ 14:43

      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.

  • Question Aug 9, 2011 @ 23:34

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

  • Ankit Aug 25, 2011 @ 8:48

    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???

  • vijay Oct 11, 2011 @ 4:39

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

  • Asghar Ali Oct 30, 2011 @ 13:11

    Thanks Dude! I really need it.

  • Asghar Ali Mar 31, 2012 @ 19:33

    Thank you so much! it really helped..

  • Mykhailo Jun 24, 2012 @ 9:35


    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.

  • Captain Mac Jun 26, 2012 @ 23:28

    “\\; ” 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?

  • Mykhailo Jul 7, 2012 @ 12:48

    Captain Mac June 26, 2012 at 11:28 pm
    “\\; ” 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 :(

  • Captain Mac Jul 9, 2012 @ 6:33

    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.

  • Mykhailo Jul 19, 2012 @ 17:14

    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.


  • Mykhailo Jul 19, 2012 @ 17:19

    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 –

  • Sanjeev Aug 22, 2012 @ 12:43

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

  • Neeraj Oct 9, 2012 @ 6:25

    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

    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


  • Vitalij Oct 17, 2012 @ 19:24

    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 ;)

  • Niki Jul 19, 2013 @ 8:59

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

    • Vern Aug 21, 2014 @ 15:10

      man find

  • komischer vogel May 6, 2014 @ 23:23


    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?

    • komischer vogel May 7, 2014 @ 13:15

      ok found it out myself:


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

  • RK May 20, 2015 @ 20:01

    How do you log the output somewhere which files were successfully deleted or not in the find and delete command?

  • solak Sep 24, 2015 @ 18:19

    To delete files that contain certain strings, just include a test of that as a condition of the find before you do the deletion. Let’s say you want to get rid of text files that have empty parentheticals, those (), [], and {} that you mention. Just have grep look for them. To make it interesting, I’ve added optional spaces within the empty grouping characters and made the deletion optional. To make it more interesting, you could also accept tabs as whitespace or use egrep and put all the tests in one regular expression.

    find this-dir that-dir -name \*.txt -exec grep -q -e ‘( *)’ -e ‘\[ *]’ -e ‘{ *}’ \{} \; -ok rm -f \{} \;

    So, this starts searching at this-dir and at that-dir looking inside there for files whose names end with .txt, and then it silently searches the file content for various kinds of parentheses wrapped around zero or more spaces. For each of those, it asks you whether to delete the file.

  • s0l0m0n Oct 6, 2015 @ 16:22

    Thanks for awesome example
    I would like to keep file last 3 month.
    The command below

    $ find . -mtime +90 -type f -exec rm -f {} \;

  • David Nov 2, 2015 @ 15:38

    If you use find with -depth, it will start the delete from the deepest folder first.
    So if I have ./temp, ./temp/temp1, and ./temp1/temp2

    find $HOME -depth ./temp -delete (or find $HOME -depth ./temp -exec rm -rf {} \; )
    will delete ./temp/temp1/temp2, then ./temp/temp1, and finally ./temp

  • cg Nov 17, 2015 @ 4:07

    find /Volumes/CONVERT -type d -name “folder” -exec rm -rf {} \;
    Running the above command on my shared storage works, but produces an odd permission issue. I have mac and windows clients attached to the shared volume “CONVERT”. My windows machines will try to create a folder or file with the same name, but will claim they don’t have permission to do so, or they will say the folder/file already exists when it in fact it does not exist. I thought the mac was re-writing the permissions, but the permissions aren’t actually changing, the only problem is when the windows machines try to create a folder/file with the same name as the folder/file that was removed with the above command. Hope this makes sense, it’s kind of confusing. The folders/files that I’m trying to remove are temporary folders/files that are being automatically generated by software running on the mac and windows clients. I would like to remove all of them every now and again to free-up space on my server, however it will cause issues if my computers can’t re-generate these folders and files it will cause lots of errors and problems.

    Anybody else run into an issue like this?

  • Charles Nov 21, 2015 @ 2:52

    Can you happen to tell me how to add a file size limit to this.

    This works: find /home -name "error_log" -exec rm -rf {} \;

    I tried this but it does not work:

    find /home -size +5000000b -name "error_log" -exec rm -rf {} \;

    It doesn’t remove any files.


  • Aaron May 2, 2016 @ 14:46


  • Tom Nov 4, 2016 @ 13:47

    not working:
    find / -name “*jpg.lck” -exec rm -rf {}\;
    find: missing argument to `-exec’

    what do i wrong?

  • Justin Bibi Jan 2, 2017 @ 11:43

    hi. sorry to disturb you.
    happy new year
    can you help me with my bash shell scripting?
    I have list.txt and each line inside it is a filename which sometimes contains special character and spaces. those files listed in list.txt is stored at /tmp/fordel directory. now my script is not working in deleting those files. Im using bash shell account.
    delfile.script below:

    cd $FOLDER
    sed -i '/^\s*$/d' $FOLDER/list.txt
    cat $FOLDER/list.txt | while read -r line
            cd $FOLDER
           find $FOLDER -iname "$line" -exec rm {} \;
    echo "Done"

    i need help pls what that find is not working or any other option?

  • Jeff Madson Feb 26, 2021 @ 15:15

    I run the find/delete command on my entire hard drive (/). Because it’s looking at the entire drive for a file, I get this message over and over again and it takes a very long time: find: /System/Volumes/Data/private/var/folders/kx/d4f9r91x4qqfzcs0fyrkq_pc0000gp/0/ Operation not permitted.
    I’m assuming that these locations are all locked down in Catalina/Big Sur. Is there a way to not scan locked directories? Thanks a lot for your help!

    • 🐧 Vivek Gite Feb 26, 2021 @ 19:12

      You need to give Terminal app full disk access. \

      There is also xattr command.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum