1、多行變成單行
-bash-3.2# cat test.txt
a b c d e f
g o p q
-bash-3.2# cat test.txt |xargs
a b c d e f g o p q
2、單行變成多行
-bash-3.2# cat test.txt
a b c d e f g o p q
-bash-3.2# cat test.txt |xargs -n 2
a b
c d
e f
g o
p q
3、刪除某個重復的字符來做定界符
-bash-3.2# cat test.txt
Aaaagttttgyyyygcccc
-bash-3.2# cat test.txt |xargs -d g
aaaa tttt yyyy cccc
4、刪除某個重復的字符來做定界符后,變成多行
-bash-3.2# cat test.txt |xargs -d g -n 2
aaaa tttt
yyyy cccc
5、用find找出文件以txt后綴,並使用xargs將這些文件刪除
-bash-3.2# find /root/ -name "*.txt" -print #查找
/root/2.txt
/root/1.txt
/root/3.txt
/root/4.txt
-bash-3.2# find /root/ -name "*.txt" -print0 |xargs -0 rm -rf #查找並刪除
-bash-3.2# find /root/ -name "*.txt" -print #再次查找沒有
6、查找普通文件中包括thxy這個單詞的
-bash-3.2# find /root/ -type f -print |xargs grep "thxy"
/root/1.doc:thxy
7、查找權限為644的文件,並使用xargs給所有加上x權限
-bash-3.2# find /root/ -perm 644 -print
/root/1.c
/root/5.c
/root/2.doc
/root/3.doc
/root/1.doc
/root/2.c
/root/4.doc
/root/4.c
/root/3.c
-bash-3.2# find /root/ -perm 644 -print|xargs chmod a+x
-bash-3.2# find /root/ -perm 755 -print
/root/1.c
/root/5.c
/root/2.doc
/root/3.doc
/root/1.doc
/root/2.c
/root/4.doc
/root/4.c
/root/3.c
8、ps -ef|grep LOCAL=NO|grep -v grep|cut -c 9-15|xargs kill -9
運行這條命令將會殺掉所有含有關鍵字"LOCAL=NO"的進程:
管道符"|"用來隔開兩個命令,管道符左邊命令的輸出會作為管道符右邊命令的輸入。
"ps -ef" 是linux里查看所有進程的命令。這時檢索出的進程將作為下一條命令"grep LOCAL=NO"的輸入。
"grep LOCAL=NO" 的輸出結果是,所有含有關鍵字"LOCAL=NO"的進程。
"grep -v grep" 是在列出的進程中去除含有關鍵字"grep"的進程。
"cut -c 9-15" 是截取輸入行的第9個字符到第15個字符,而這正好是進程號PID。
"xargs kill -9" 中的 xargs 命令是用來把前面命令的輸出結果(PID)作為"kill -9"命令的參數,並執行該命令。"kill -9"會強行殺掉指定進程。
其它類似的情況,只需要修改"grep LOCAL=NO"中的關鍵字部分就可以了。
另一種方法,使用awk
ps x|grep gas|grep -v grep |awk '{print $1}'|xargs kill -9
另:
xargs 與find 命令合用的時候,find 把匹配到得命令傳遞給xargs ,xargs 每次只獲取一部分文件,而不是全部。分批處理。
xargs則只有一個進程、但xargs 處理是否分批 ,批次大小,也會受系統些可調參數影響。