xargs命令把從stdin接收到的數據重新格式化,再將其作爲參數提供給其他命令。
1.將多行輸入轉換爲單行輸出
$ cat example.txt #樣例文件 1 2 3 4 5 6 7 8 9 10 11 12
$ cat example.txt | xargs 1 2 3 4 5 6 7 8 9 10 11 12
2.將單行輸入轉換成多行輸出
$ cat example.txt | xargs -n 3 #每行n個參數,空格是默認的定界符 1 2 3 4 5 6 7 8 9 10 11 12
3.自定義分界符
$ echo "splitXsplitXsplitXsplit" | xargs -d X split split split split
$ echo "splitXsplitXsplitXsplit" | xargs -d X -n 2 split split split split
4.將參數傳遞給命令
$ cat cecho.sh #測試腳本 #!/bin/bash #filename: cecho.sh echo $* '#'
$ ./cecho.sh arg1 arg2 arg1 arg2#
$ cat args.txt | xargs -I {} ./cecho.sh -p {} -l -p arg1 -l # -p arg2 -l # -p arg3 -l #
5.find+xargs
$ ls args.txt cecho.sh example.txt
$ find . -type f -name "*.txt" -print0 | xargs -0 rm -f
$ ls cecho.sh
參考:
[1] Sarath Lakshman. Linux Shell Scripting Cookbook. PACKT PUBLISHING