xargs命令是給其他命令傳遞參數的一個過濾器,也是組合多個命令的一個工具。它擅長將標準輸入數據轉換成命令行參數,xargs能夠處理管道或者stdin並將其轉換成特定命令的命令參數。
xargs也可以將單行或多行文本輸入轉換爲其他格式,例如多行變單行,單行變多行。xargs的默認命令是echo,空格是默認定界符。
這意味着通過管道傳遞給xargs的輸入將會包含換行和空白,不過通過xargs的處理,換行和空白將被空格取代。xargs是構建單行命令的重要組件之一。
多行輸入單行輸出:
[root@localhost test]# cat a.log |xargs
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@localhost test]# cat a.log |xargs -n5
d e f g h
i j k l m
n o p q r
s t u v w
x y z
-d選項可以自定義一個定界符:
[root@localhost test]# echo "nameXnameXnameX"|xargs -dX
name name name
結合-n選項使用:
[root@localhost test]# echo "nameXnameXnameX"|xargs -dX -n1
name
name
name
- xargs結合find使用
[root@localhost test]# cat a.sh
#!/bin/bash
echo $*
授權
[root@localhost test]# chmod 777 a.sh
[root@localhost test]# cat b.txt
aaa
bbb
ccc
[root@localhost test]# cat b.txt |xargs -I {} ./a.sh begin {} end
begin aaa end
begin bbb end
begin ccc end
用rm 刪除太多的文件時候,可能得到一個錯誤信息:/bin/rm Argument list too long. 用xargs去避免這個問題
[root@localhost test]# find . -type f -name "*.log" -print0|xargs -0 rm -f
xargs -0將\0作爲定界符。
統計一個源代碼目錄中所有php文件的行數:
[root@localhost test]# find . -type f -name "*.js" -print0|xargs -0 wc -l
查找所有的jpg 文件,並且壓縮它們:
[root@localhost test]# find . -type f -name "*.jpg" -print|xargs tar -czvf image.tar.gz
假如你有一個文件包含了很多你希望下載的URL,你能夠使用xargs下載所有鏈接:
[root@localhost test]#cat url-list.txt | xargs wget -c