find最普通的用法是查找文件,然后要对文件进行处理就需要用到参数-exec。
先看下manpage中介绍:
-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 argu‐ ments 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 section for examples of the use of the -exec option. The specified 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 action; you should use the -execdir option instead.
-exec 参数后面跟的是command命令,它的终止是以;为结束标志的,所以这句命令后面的分号是不可缺少的,考虑到各个系统中分号会有不同的意义,所以前面加反斜杠。
{} 花括号代表前面find查找出来的文件名。
使用find时,只要把想要的操作写在一个文件里,就可以用exec来配合find查找,很方便的。在有些操作系统中只允许-exec选项执行诸如l s或ls -l这样的命令,需要测试。大多数用户使用这一选项是为了查找旧文件并删除它们。建议在真正执行rm命令 删除文件之前,最好先用ls命令看一下,确认它们是所要删除的文件。 为了使用exec选项,必须要同时使用print选项。如果验证一下find命令,会发现该命令只输出从当前路径起的相对路径及文 件名。
看几个例子:
把所有普通文件复制到~/tmp/目录下~$find . -type f -print -exec cp {} ~/tmp/ \;
复制文件内容到当前目录所有普通文件find . -type f -print -exec cp ~/route {} \;
find . -type f -print -exec rm {} \;
参考: