A seemingly underused feature of find is its -exec feature. Undoubtedly, the main reason for this is the rather confusing covereage of this feature in find’s man page, which I reproduce for you here:
-exec utility [argument …];
True if the program named utility returns a zero value as its
exit status. Optional arguments may be passed to the utility.
The expression must be terminated by a semicolon (“;”). If the
string “{}” appears anywhere in the utility name or the argu-
ments it is replaced by the pathname of the current file.
Utility will be executed from the directory from which find was
executed. Utility and arguments are not subject to the further
expansion of shell patterns and constructs.
Whenever I needed to do such a task, I found myself fumbling with xargs, pipes, outputting to a file and manipulating the resultant text with other programs, etc. I always looked at -exec with great hope and wonder, but always walked away thinking it did not offer me the functionality I seeked. I admit, looking at the man page now, it clearly describes exactly what -exec does and how to use it. But I swear, I read that thing 10 times over the course of 5 years and it never clicked. I think what threw me was the first sentence, which made me gather that it was some sort of tool to do an audit of a boolean characteristic of each file in the search results. Referring to a program/command/binary as a “utility” also doesn’t really help things.
But recently I found a page on the web, I believe it was this one, that showed me the -exec flag does exactly what I need.
The key is knowing that {} should be placed where each result of find should be placed in the desired command, and the series of flags should be terminated with \;.
For example, If you want to check the syntax on each php file in a tree by executing php -l on each, you would use this command:
find . -name "*.php" -exec php -l {} \;
Awesome.
Latest Comments
RSS