find是一个非常常用的Linux命令,但是我们一般查出来的不只是看看,还要进行进一步的操作。这时候exec的作用就显露出来了。exec说明:-exec参数后面跟command命令,它的终止用;标示,所以这个命令后面的分号是必不可少的。考虑到分号在每个系统中会有不同的含义,所以在它前面加一个反斜杠。{}花括号代表之前find找到的文件名。在使用find的时候,只要把需要的操作写在一个文件中,就可以用exec配合find进行查找,非常方便。在某些操作系统上,只允许-exec选项执行命令,例如ls或ls-l。大多数用户使用此选项来查找旧文件并删除它们。建议在真正执行rm命令删除文件之前,最好先用ls命令查看一下,确认就是要删除的文件。exec选项后跟要执行的命令或脚本,然后是一对{}、一个空格和一个\,最后是一个分号。为了使用exec选项,还必须使用print选项。如果你验证find命令,你会发现该命令只输出当前路径的相对路径和文件名。例1:ls-l命令放在find命令的-exec选项中命令:find。-typef-execls-l{}\;输出:[root@localhosttest]#find.-typef-execls-l{}\;-rw-r--r--1rootroot12710-2816:51./log2014.log-rw-r--r--1rootroot010-2814:47./test4/log3-2.log-rw-r--r--1rootroot010-2814:47./test4/log3-3.log-rw-r--r--1rootroot010-2814:47。/test4/log3-1.log-rw-r--r--1rootroot3310-2816:54./log2013.log-rw-r--r--1rootroot30210811-0306:19./log2012.log-rw-r--r--1rootroot2510-2817:02./log.log-rw-r--r--1rootroot3710-2817:07。/log.txt-rw-r--r--1rootroot010-2814:47./test3/log3-2.log-rw-r--r--1rootroot010-2814:47./test3/log3-3.log-rw-r--r--1rootroot010-2814:47./test3/log3-1.log[root@localhosttest]#说明:在上面例如,find命令匹配当前目录下的所有普通文件,并在-exec选项中使用ls-l命令列出它们。示例2:在目录中查找更改时间为n天前的文件并删除命令:find。-typef-mtime+14-execrm{}\;输出:[root@localhosttest]#lltotal328-rw-r--r--1rootroot30210811-0306:19log2012.log-rw-r--r--1rootroot3310-2816:54log2013.log-rw-r--r--1rootroot12710-2816:51log2014.loglrwxrwxrwx1rootroot710-2815:18log_link.log->log.log-rw-r--r--1rootroot2510-2817:02log.log-rw-r--r--1rootroot3710-2817:07log.txtdrwxr-xr-x6rootroot409610-2701:58scfdrwxrwxrwx2rootroot409610-2814:47test3drwxrwxrwx2rootroot409610-2814:47test4[root@localhosttest]#find.-typef-mtime+14-execrm{}\;[root@localhosttest]#lltotal312-rw-r--r--1rootroot30210811-0306:19log2012.loglrwxrwxrwx1rootroot710-2815:18log_link.log->log.logdrwxr-xr-x6根根409610-2701:58scfdrwxrwxrwx2根根409611-1219:32test3drwxrwxrwx2根根409611-1219:32test4[root@localhosttest]#说明:使用shell中的任意方法删除文件前,应先检查对应的文件,小心!当使用mv或rm等命令时,您可以使用-exec安全模式选项,它会在对每个匹配文件执行操作之前提示您。例3:查找目录下更改时间为n天前的文件并删除,删除前提示命令:find。-name"*.log"-mtime+5-okrm{}\;输出:[root@localhosttest]#lltotal312-rw-r--r--1rootroot30210811-0306:19log2012.loglrwxrwxrwx1rootroot710-2815:18log_link.log->log.logdrwxr-xr-x6rootroot409610-2701:58scfdrwxrwxrwx2rootroot409611-1219:32test3drwxrwxrwx2rootroot409611-1219:32test4[root@localhosttest]#find.-name"*.log"-mtime+5-okrm{}\;
