This blog has moved! Redirecting...
You should be automatically redirected. If not, visit http://scrolls.mafgani.net/ and update your bookmarks.

Wednesday, March 26, 2008

Processing files using 'find'

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 removes all *.doc files from the current directory would be:

$ find . -name \*.doc -exec rm {} \;