find -exec 与xargs 区别

find . -name "*.txt" -exec rm {} \;
find . -name "*.txt" | xargs rm {} 


-exec
    1.参数是一个一个传递的,传递一个参数执行一次rm
    2.文件名有空格等特殊字符也能处理
-xargs 
    1.一次将参数传给命令,可以使用-n控制参数个数
    2.处理特殊文件名需要采用如下方式:
    find . -name "*.txt" print0 |xargs -0 rm {} 

实验结果如下,可以清楚看到参数传递过程

  1. [root@andes.com ~/tmp/dir]#find . -type f |xargs -t -n 2 echo  
  2. echo ./data.txt ./env2.txt   
  3. ./data.txt ./env2.txt  
  4. echo ./env.txt ./export2.txt   
  5. ./env.txt ./export2.txt  
  6. echo ./s.txt ./d.txt   
  7. ./s.txt ./d.txt  
  8. echo ./export.txt ./set.txt   
  9. ./export.txt ./set.txt  
  10. echo ./fuck.txt   
  11. ./fuck.txt  
  12. [root@andes.com ~/tmp/dir]#find . -type f -exec echo begin {} \;  
  13. begin ./data.txt  
  14. begin ./env2.txt  
  15. begin ./env.txt  
  16. begin ./export2.txt  
  17. begin ./s.txt  
  18. begin ./d.txt  
  19. begin ./export.txt  
  20. begin ./set.txt  
  21. begin ./fuck.txt  
  22. [root@andes.com ~/tmp/dir]#  


技巧: find -print0  与 xargs -0 的结合避免文件名有特殊字符如空格,引号等无法处理:

 find . -name "*.txt" print0 |xargs -0 rm {} 

find 

       -print True; print the full file name on the standard output, followed by a newline.   If you are piping the
              output of find into another program and there is the faintest possibility that the  files  which  you
              are  searching  for  might  contain  a  newline, then you should seriously consider using the -print0
              option instead of -print.  See the UNUSUAL FILENAMES section for information about how unusual  char-
              acters in filenames are handled.


       -print0
              True;  print  the full file name on the standard output, followed by a null character (instead of the
              newline character that -print uses).  This allows file names that contain newlines or other types  of
              white space to be correctly interpreted by programs that process the find output.  This option corre-
              sponds to the -0 option of xargs.

xargs 

       -0     Input items are terminated by a null  character  insteadof  by
     whitespace,  and the quotes and backslash are not special (every
     character is taken literally).  Disables the end of file string,
     which  istreated  likeany other argument.  Useful when input
     items might contain white space, quote  marks,  or  backslashes.
     The  GNU find  -print0  option produces input suitable for this
     mode.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值