Linux pipe find with rm

find /path/to/dir -name name_of_file_to_match | xargs /bin/rm

I use often the above command to clean a directory from all the back up files created by emacs, so for example if I am developing a site at: /var/www/a-site/ then at the end of the day or at the beginning of a new one I clean up the directory as follow:
find /var/www/a-site -name '*~' | xargs rm
Be careful with the above command, specially if you run it as root and you get wrong the regex you could delete things you didn’t mean to !

8 thoughts on “Linux pipe find with rm

  1. Thanks Florian,
    you are absolutely right, rm will be executed for each file discovered by find.
    The curly brackets {} are replaced with the current discovered file.
    The semicolon ; signals the end of the arguments passed to rm
    The backslash \ escapes the semicolon ;

  2. I know this is resurrecting an old thread, but I want future finders of this article to see the answer to John V. Kjellman’s question, which is quite important… Yes, you can use the ‘-i’ argument, which is a very good idea! The command would look something like this (for example, I’m looking to remove all .DS_Store files from the current and nested folders):$find . -name “.DS_Store” -exec rm -i {} \;If you anticipate a lot of files to remove, obviously you may not want to take the time to approve every remove. If after a few results, you are comfortable doing so, you could stop the command with ^c and then re-execute it without the ‘-i’ argument:$find . -name “.DS_Store” -exec rm {} \;Hope this helps someone out there!-Christo

  3. If you only want to delete files, you can do it in a single processfind /path/to/dir -name name_of_file_to_match -delete

Leave a Reply

Your email address will not be published. Required fields are marked *