Processing files using ‘find’
by Mostafa on Mar.26, 2008, under How To ..., Linux, Software
In its most basic form, find is often used to locate files that are subsequently piped through a complex set of commands for processing. However, this particular method is easily broken by files that contain spaces in their names.
This is where the ‘exec’ option provided by find comes in handy. From the man-page:
-exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of ‘;’ is encountered. The string ‘{}’ is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a ‘\’) or quoted to protect them from expansion by the shell. See the EXAMPLES sec- tion for examples of the use of the ‘-exec’ option. The speci- fied command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec option; you should use the -execdir option instead.
An example that recursively touches all *.log files from the current directory would be:
$ find . -name \*.log -exec touch {} \;
March 26th, 2010 on 3:12 pm
Yes, that is useful but your example may trick people into using it for deleting files. The –delete option for find is better suited for that, as it changes path traversal order.
March 26th, 2010 on 8:43 pm
Thanks for that. While it certainly wasn’t my intention, it’s good to be made aware of the possible implications.