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 {}
实验结果如下,可以清楚看到参数传递过程
- [root@andes.com ~/tmp/dir]#find . -type f |xargs -t -n 2 echo
- echo ./data.txt ./env2.txt
- ./data.txt ./env2.txt
- echo ./env.txt ./export2.txt
- ./env.txt ./export2.txt
- echo ./s.txt ./d.txt
- ./s.txt ./d.txt
- echo ./export.txt ./set.txt
- ./export.txt ./set.txt
- echo ./fuck.txt
- ./fuck.txt
- [root@andes.com ~/tmp/dir]#find . -type f -exec echo begin {} \;
- begin ./data.txt
- begin ./env2.txt
- begin ./env.txt
- begin ./export2.txt
- begin ./s.txt
- begin ./d.txt
- begin ./export.txt
- begin ./set.txt
- begin ./fuck.txt
- [root@andes.com ~/tmp/dir]#
技巧: find -print0 与 xargs -0 的结合避免文件名有特殊字符如空格,引号等无法处理:
find . -name "*.txt" print0 |xargs -0 rm {}