Expressions that take action on files selected by find



Last revision July 20, 2004

Additional topics:

find includes a second type of expression: an "action" expression that performs an action on the files that have been selected, and may also further restrict the set of files to be selected for the next level.

Here are the most generally useful "action" expressions. Again, see the on-line manual entry for a complete list.

-print

Causes the names of the selected files (pathnames relative to those in the pathname list) to be printed to the standard output file (normally the terminal). If you want to see which files are selected, you should include this expression. On pangea, this expression is the default action if no other actions are specified. This expression does not impose any further selection criteria. That is, after printing the filenames, this expression passes them all on to the next expression (if any). On pangea and many other Unix systems, there is an alternate form -ls which gives a "long listing" containing information similar to the output of a separate ls -l command, including file permissions, ownership, date, etc.

-exec command {} \;
The -exec action executes any arbitrary command on each selected file, whose file pathname is substituted wherever the string {} appears. The entire action expression must be terminated by the escaped semi-colon (\;), so find knows where the command ends and the next expression begins. Examples:

-exec rm {} \;
Removes the files that match the selection criteria.

-exec grep -l keyword {} \;
Runs the grep program on each file, looking for lines that contain keyword. In this case, the -l option to grep says to only print the names of the files that contain the keyword, not to print the actual matching lines.

The -exec expression is also a selection expression in this sense: a file matches the -exec expression, and is selected for further processing by subsequent expressions, if the exit status of the command is zero (successful). If the command does not execute successfully, then the file is not selected for further expressions, although this action has already been completed.

-ok
This action has the same syntax and arguments as the -exec action and works just like it, except that the find program displays each command that it intends to execute on the terminal (standard output) and prompts for a confirmation that you really want to execute it. If you respond to the prompt with anything other than y, the command is not executed and the file "fails" this selection (not passed on to further expressions). Example:

-ok rm {} \;

will prompt you for permission to remove each selected file.