xargs入门

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章