原理詳見 https://www.cnblogs.com/f-ck-need-u/p/5925923.html
0. xargs概述:
whereis xargs
: #二進(jìn)制文件、源蛮穿、使用手冊(cè)位置
xargs: /usr/bin/xargs /home/xxx/sbin/xargs /home/work/xxx/bin/xargs /usr/share/man/man1p/xargs.1p.gz /usr/share/man/man1/xargs.1.gz
whatis xargs
: # xargs所在使用手冊(cè)的章節(jié)位置
xargs (1) - build and execute command lines from standard input
man xargs
: # xargs所在使用手冊(cè)的章節(jié)位置
xargs是一個(gè)強(qiáng)有力的命令榜旦,它能夠捕獲一個(gè)命令的輸出淫僻,然后傳遞給另外一個(gè)命令。
- xargs從標(biāo)準(zhǔn)輸入(stdin)中讀取待處理數(shù)據(jù)
- 待處理數(shù)據(jù)以空格進(jìn)行分隔
- 可以根據(jù)參數(shù)進(jìn)行一次或多次處理, 默認(rèn)命令是echo厕九,
- 忽略空行
- 遇到命令狀態(tài)為255時(shí), xargs會(huì)立刻停止,譬如發(fā)生錯(cuò)誤時(shí).
命令格式:
somecommand | xargs -item command
1. 為什么要用xargs?
有些時(shí)候我們需要對(duì)一些linux操作進(jìn)行處理,比如
-
現(xiàn)在有單個(gè)進(jìn)程pc_driver题翻,如何快速kill?
現(xiàn)在想要kill這個(gè)進(jìn)程腰鬼。使用ps -ef|grep pc_driver| kill
管道是不可行的嵌赠,
換個(gè)方法塑荒,使用如下命令,其效果類似
kill $PID
kill `ps -ef|grep pc_driver`
- 考慮進(jìn)程變多了呢猾普?有很多
pc_driver
的進(jìn)程袜炕,該如何快速處理呢?
方法1:與kill 單個(gè)進(jìn)程一樣初家,使用for循環(huán)處理偎窘。for pid in $(ps -ef | grep pc_driver | awk '{print $2}'); do kill -9 $pid; done
方法2:使用xargs。ps -ef | grep pc_driver | awk '{print $2}' | xargs kill
2. xargs和管道的區(qū)別溜在?
-
管道:‘|’是將前面的標(biāo)準(zhǔn)輸出作為后面的標(biāo)準(zhǔn)輸入陌知;比如
echo "hello" | cat
相當(dāng)于將echo的內(nèi)容"hello"當(dāng)作cat處理的文件內(nèi)容了,相當(dāng)于hello.txt文件有一行內(nèi)容hello,然后cat hello.txtimage.png -
xargs:是將標(biāo)準(zhǔn)輸入作為命令的參數(shù);比如
echo "hello" | xargs cat
相當(dāng)于cat hello
2. xargs的常用操作命令
-a 選項(xiàng): 處理文本
-n 選項(xiàng): 將數(shù)據(jù)按照(-n 后的數(shù)字)分組, 默認(rèn)按照空格劃分
-d 選項(xiàng): 分隔符掖肋,默認(rèn)的xargs分隔符是回車
-t 選項(xiàng): 在每次執(zhí)行xargs后面的命令都會(huì)先打印一遍命令后才正式執(zhí)行
-p 選項(xiàng): 交互式處理
-E 選項(xiàng): 傳遞終止符仆葡。注-E只有在xargs不指定-d的時(shí)候有效,如果指定了-d則不起作用志笼,而不管-d指定的是什么字符沿盅,空格也不行
測(cè)試txt內(nèi)容如下
1, 2, 3, 4, 5, 6, 7, 8, 9
a, b, c, d, e, f, g, h, i
(1) 執(zhí)行 cat test.txt | xargs
,或者 cat test.txt | xargs -a test.txt
測(cè)試結(jié)果
1, 2, 3, 4, 5, 6, 7, 8, 9 a, b, c, d, e, f, g, h, i
(2) 執(zhí)行 cat test.txt | xargs -n 3
, 測(cè)試結(jié)果
1, 2, 3,
4, 5, 6,
7, 8, 9
a, b, c,
d, e, f,
g, h, i
(3) 執(zhí)行cat test.txt | xargs -d ","
, 測(cè)試結(jié)果
1 2 3 4 5 6 7 8 9
a b c d e f g h i
(4) 執(zhí)行cat test.txt | xargs -n 3 -t
, 測(cè)試結(jié)果
/bin/echo 1, 2, 3,
1, 2, 3,
/bin/echo 4, 5, 6,
4, 5, 6,
/bin/echo 7, 8, 9
7, 8, 9
/bin/echo a, b, c,
a, b, c,
/bin/echo d, e, f,
d, e, f,
/bin/echo g, h, i
g, h, i
(4) 執(zhí)行cat test.txt | xargs -n 3 -p
, 測(cè)試結(jié)果
(5) 執(zhí)行
echo 'a b c' | xargs -E 'c' echo
, 測(cè)試結(jié)果