How to delete files of certain name from terminal recursively

Kostas picture Kostas · Mar 17, 2017 · Viewed 7.1k times · Source

I would like to delete all the emacs backup (~) files from subfolders. I am aware that I can cd in every single folder and delete them using rm *~ (e.g. for backup file test.cpp~).

How I can delete these files with one command, without cd'ing in every folder?

(I tried rm -r *~ and rm -rf *~ but they don't seem to work)

Answer

Leo Izen picture Leo Izen · Mar 17, 2017

You can do this with find and exec. Here's an example that does what you want to do:

find -name '*~' -exec rm {} \;

Let's break it down how this works. The find command will recurse through the directory it's executed from, and by default it will print out everything it finds. Using -name '*~' tells us only to select entries whose name matches the regex *~. We have to quote it because otherwise the shell might expand it for us. Using -exec rm {} will execute rm for each thing it finds, with {} as a placeholder for the filename. (The final ; is something required to tell find that this is where the command ends. It's not really a big deal but it'll whine and do nothing if you don't use it. The \ is to escape it because ; is a special shell character.)