概述
xargs命令是給其他命令傳遞參數的一個過濾器,也是組合多個命令的一個工具。
它擅長將標準輸入數據轉換成命令行參數,xargs能夠處理管道或者stdin并將其轉換成特定命令的命令參數。
xargs也可以將單行或多行文本輸入轉換為其他格式,例如多行變單行,單行變多行。
xargs的默認命令是echo,空格是默認定界符。
這意味著通過管道傳遞給xargs的輸入將會包含換行和空白,不過通過xargs的處理,換行和空白將被空格取代。
xargs是構建單行命令的重要組件之一。
語法
[root@entel2 ~]# xargs --help
Usage: xargs [-0prtx] [--interactive] [--null] [-d|--delimiter=delim]
[-E eof-str] [-e[eof-str]] [--eof[=eof-str]]
[-L max-lines] [-l[max-lines]] [--max-lines[=max-lines]]
[-I replace-str] [-i[replace-str]] [--replace[=replace-str]]
[-n max-args] [--max-args=max-args]
[-s max-chars] [--max-chars=max-chars]
[-P max-procs] [--max-procs=max-procs] [--show-limits]
[--verbose] [--exit] [--no-run-if-empty] [--arg-file=file]
[--version] [--help] [command [initial-arguments]]
Report bugs to <bug-findutils@gnu.org>.
栗子
xargs用作替換工具,讀取輸入數據重新格式化后輸出。
定義一個測試文件,內有多行文本數據:
[root@entel2 ~]# cat xargs.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
多行輸入單行輸出
[root@entel2 ~]# cat xargs.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
[root@entel2 ~]# cat xargs.txt |xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z
-n選項多行輸出
[root@entel2 ~]# cat xargs.txt | xargs -n5
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
z
[root@entel2 ~]#
-d選項可以自定義一個定界符:
[root@entel2 ~]# echo "nameXnameXnameXname" | xargs -dX
name name name name
結合-n選項使用
[root@entel2 ~]# echo "nameXnameXnameXname" | xargs -dX -n2
name name
name name
讀取stdin,將格式化后的參數傳遞給命令
假設一個命令為 xgj.sh 和一個保存參數的文件args.txt:
args.txt已經具備執行權限
[root@entel2 test]# cat xgj.sh
#!/bin/bash
#打印所有的參數
echo $*
[root@entel2 test]# cat args.txt
aaa
bbb
ccc
xargs的一個選項-I,
使用-I指定一個替換字符串{},
這個字符串在xargs擴展時會被替換掉,當-I與xargs結合使用,每一個參數命令都會被執行一次:
[root@entel2 test]# cat args.txt | xargs -I {} ./xgj.sh XXX {} YYY
XXX aaa YYY
XXX bbb YYY
XXX ccc YYY
復制所有圖片文件到 /data/images 目錄下:
ls *.jpg | xargs -n1 -I cp {} /data/images
xargs結合find使用
用rm 刪除太多的文件時候,可能得到一個錯誤信息:
/bin/rm Argument list too long.
用xargs去避免這個問題:
find . -type f -name "*.log" -print0 | xargs -0 rm -f
xargs -0將\0作為定界符。
統計一個源代碼目錄中所有py文件的行數:
find . -type f -name "*.py" -print0 | xargs -0 wc -l
查找所有的jpg 文件,并且壓縮它們:
find . -type f -name "*.jpg" -print | xargs tar -czvf images.tar.gz
xargs其他應用
假如你有一個文件包含了很多你希望下載的URL,你能夠使用xargs下載所有鏈接:
cat url-list.txt | xargs wget -c