Find is a fine command of itself, however what elevates find to the next level is its ability to execute other commands. The argument for that is -exec.
-exec consists of 3 parts:
- command
- arguments
- delimiter
The syntax is:
find <path/to/search> [search expression] -exec <command> <arguments> <delimiter>
The command
This is just any command that can be executed by the shell. There are caveats here, as aliases and user defined functions are not available. The reason is that is exec running your command and not the shell.
The arguments
These are the arguments, options, etc. to be passed to the command just like they would be given to the shell.
The results argument {}
When using -exec, find provides a special argument {} which contains the result of the current search. It can be used as needed in your arguments.
The delimiter
The delimiter is used to indicate the end of the command to -exec. It comes in two flavors: + and \;.
The + delimiter concatenates all results in one single string and puts them in {}. The command (with all the arguments), will be run only once.
The \; delimiter (the actual delimiter is ;, however it must be escaped with a backslash to prevent the shell from interpreting it) will call command once per result, {} will contain only this one result.
Examples:
Count the lines of each Fortran file:
find . -name "*.f90" -exec wc -l {} \;
Find all Fortran files with comments containing the string “J.L.” (case-insensitive):
find . -name ".f90" -exec grep -iE "!\.*j.l." {} \;