Executing commands for each result

Perhaps the most powerful action available in find is -exec, which allows you to run a command on each of the found results. This is best explained by an example; this command looks for occurrences of the search string in all files with names ending in .vim in a directory named vim:

$ find vim -type f -name '*.vim' -exec grep -F search -- {} \;

The -exec action here is followed by the name of the grep tool, its -F option, a "search" pattern, an option terminator (--), and two special arguments:

  • {}: Replaced with each find result
  • \;: Terminates the command
Note that we have to escape the semicolon with a backslash, in order to prevent Bash from interpreting it itself. Putting it in single quotes or double ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.