當 find 找到大量檔案並交給其他指令處理時,常會跳出「參數列太長」或「參數列溢出」的錯誤。這正是 xargs 派上用場的時刻,尤其它與 find 搭配時最為靈活。
find 會把比對到的檔案交給 xargs,而 xargs 每次只取一部分檔案而非一次全給,不像 -exec 那樣。因此它能先處理第一批,再處理下一批,如此反覆。此外,某些系統用 -exec 時會為每個檔案各起一個程序,檔案一多就容易造成程序暴增、效能下滑;而 xargs 只會有一個程序。究竟一次取全部還是分批、每批取多少,則取決於指令選項與系統核心的可調參數。
範例 1:找出系統每個普通檔案並判斷其類型。
find . -type f -print | xargs file
輸出:
[root@localhost test]# find . -type f -print | xargs file
./log2014.log: empty
./log2013.log: empty
./log2012.log: ASCII text
範例 2:全系統搜尋 core dump 檔並存到 /tmp/core.log。
find / -name "core" -print | xargs echo "" >/tmp/core.log
範例 3:找目前目錄下所有人皆有讀寫執行權限的檔案,並收回寫權限。
find . -perm -7 -print | xargs chmod o-w
執行後 scf、test3、test4 等目錄權限都會改變。
範例 4:用 grep 在所有普通檔案中搜尋 hostname。
find . -type f -print | xargs grep "hostname"
輸出:
[root@localhost test]# find . -type f -print | xargs grep "hostname"
./log2013.log:hostnamebaidu=baidu.com
./log2013.log:hostnamesina=sina.com
./log2013.log:hostnames=true
範例 5:在目前目錄所有普通檔案中搜尋 hostnames。
find . -name \* -type f -print | xargs grep "hostnames"
注意此處 \ 用來取消 * 在 shell 中的特殊意義。
範例 6:用 xargs 執行 mv,把 *.log 移到 test4。
find . -name "*.log" | xargs -i mv {} test4
範例 7:出現 xargs: argument line too long 的解法。
find . -type f -atime +0 -print0 | xargs -0 -l1 -t rm -f
說明:-l1 一次處理一個;-t 會在處理前先印出指令。
範例 8:-i 參數預設用 {} 代替前面輸出,-I 則可自訂替代字元(如範例中的 [])。
find . -name "file" | xargs -I [] cp [] ..
範例 9:xargs 的 -p 參數會在執行前提示確認。
find . -name "*.log" | xargs -p -i mv {} ..
輸出會顯示 mv ./log2015.log .. ?...y,輸入 y 執行、n 不執行。