Delete or grep the results of find

-exec command {} \;
  • Execute command after find. To pass results of find use {}.
  • You must put a blank before "\;". If a blank is missing, an error occurrs like below.
    $ find . -name *~ -exec rm {}\;
    find: missing argument to `-exec'
    
    $ find . -name *~ -exec rm {}\;
    find: -exec: no terminating ";" or "+"
    
  • To execute more than one command, specify multiple -exec.

Example:

find ~ -name '*bak' -exec rm {} \;
  • In above example, "rm {} \;" following "-exec" is the command to execute. Last ";" denotes the end of the parameters. "\" before ";" is needed to escape "\" so that shell does not evaluate ";".

Example:

Delete all files whose name are *~ (Emacs backup file) in home directory.

$ find ~/ -name "*~" -exec rm {} \;

Delete all .svn directories from working directory tree of Subversion.

find . -name .svn -exec rm -rf {} \;

Grep files in directory tree.
(grep option -H for printing filename headers, -n for printing line number)

find <directory> -type f -exec grep -nH <pattern> {} \;

Leave a Reply

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

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