使用exec可能存在的問題:
- 在使用find命令匹配的文件運行exec命令時,find命令會把匹配到的文件全部傳遞給exec命令,但有些系統(tǒng)對能夠傳送的exec命令有長度限制槽华;
- 在有些系統(tǒng)中阅茶,會為每個匹配的find文件執(zhí)行exec命令啟動一個進程吹榴,這些在匹配文件較多時暖哨,會造成巨大的資源浪費;
而xargs則可以解決這兩個問題:
- xargs會分頁傳送匹配的文件給命令培慌;
- xargs只會啟動一個進程運行命令岔留;
參數(shù)
使用-i參數(shù)表示:find命令的輸出用{}代替
-lN是一次處理N個參數(shù)
-t是處理之前打印出命令
示例:
- 移動文件
-i
[root@test findTest]# ls
2rd f1 F1 f1.bak F1.bak f2 F2 f2.bak F2.bak f3 F3 f3.bak F3.bak f4 f4.bak test.sh
[root@test findTest]# find . -type f -name "*.bak" | xargs -i mv {} 2rd/
[root@test findTest]# ls 2rd
3rd f1 F1 f1.bak F1.bak f2 F2 f2.bak F2.bak f3 F3 f3.bak F3.bak f4 f4.bak
[root@test findTest]#
- 移動文件
-l -t
[root@test test]# find . -type f -name "*.bak"|xargs -t -l2 -i mv {} findTest/
mv ./f3.bak findTest/
mv ./F3.bak findTest/
mv ./F1.bak findTest/
mv ./f2.bak findTest/
mv ./f4.bak findTest/
mv ./F2.bak findTest/
mv ./f1.bak findTest/
- 搜索包含特定字符的文件
[root@test test]# find . -type f| xargs grep "Everything"
./lessTest/Kconfig: Everything in tmpfs is temporary in the sense that no files will be
./moreTest/Kconfig: Everything in tmpfs is temporary in the sense that no files will be
- 確認是否繼續(xù)執(zhí)行
-p
[root@test test]# ls
catTest f1.bak f.bak findTest headTest lessTest moreTest nlTest
[root@test test]# find . -type f -name "*.bak"| xargs -p rm -f
rm -f ./f.bak ./f1.bak ?...y
[root@test test]# ls
catTest findTest headTest lessTest moreTest nlTest