find命令应用exec及xargs

本文详细介绍了Linux中find命令的-exec参数用法,通过实际案例展示了如何利用-exec参数配合find命令实现文件的查找与处理操作,如复制或删除文件等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 {} \;

 

参考:

每天一个linux命令(20):find命令之exec

xargs用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值