linux中xargs命令的各種使用技巧
xargs命令是把接收到的數(shù)據(jù)重新格式化,再將其作為參數(shù)提供給其他命令,下面介紹xargs命令的各種使用技巧,一起來(lái)看看吧。
一、將多行輸入轉(zhuǎn)換成單行輸入:
[root@host1 test]# echo -e "1 2 3 4 5 \n6 7 8 \n9 10 11 12" >example.txt [root@host1 test]# cat example.txt 1 2 3 4 5 6 7 8 9 10 11 12 [root@host1 test]# cat example.txt |xargs 1 2 3 4 5 6 7 8 9 10 11 12
將單行輸入轉(zhuǎn)換成多行輸出:
[root@host1 test]# cat example.txt | xargs -n 3 1 2 3 4 5 6 7 8 9 10 11 12
自定義定界符進(jìn)行轉(zhuǎn)換(默認(rèn)的定界符是空格):
[root@host1 test]# echo "Hello:Hello:Hello:Hello" | xargs -d : -n 2 Hello Hello Hello Hello
二、在腳本中運(yùn)用:
[root@host1 test]# cat echo.sh #!/bin/bash echo $* '^-^'
當(dāng)參數(shù)傳遞給echo.sh
后,它會(huì)將這些參數(shù)打印出來(lái),并且以"^-^"作為結(jié)尾:
[root@host1 test]# echo -e "Tom\nHarry\nJerry\nLucy" > args.txt [root@host1 test]# cat args.txt | xargs bash echo.sh Tom Harry Jerry Lucy ^-^ [root@host1 test]# cat args.txt | xargs -n 2 bash echo.sh Tom Harry ^-^ Jerry Lucy ^-^
在上面的例子中,我們把參數(shù)源都放入args.txt文件,但是除了這些參數(shù),我們還需要一些固定不變的參數(shù),比如:
[root@host1 test]# bash echo.sh Welcome Tom Welcome Tom ^-^
在上述命令執(zhí)行過(guò)程中,Tom是變量,其余部分為常量,我們可以從"args.txt"中提取參數(shù),并按照下面的方式提供給命令:
[root@host1 test]# bash echo.sh Welcome Tom [root@host1 test]# bash echo.sh Welcome Herry [root@host1 test]# bash echo.sh Welcome Jerry [root@host1 test]# bash echo.sh Welcome Lucy
這時(shí)我們需要使用xargs中-I命令:
[root@host1 test]# cat args.txt | xargs -I {} bash echo.sh Welcome {} Welcome Tom ^-^ Welcome Harry ^-^ Welcome Jerry ^-^ Welcome Lucy ^-^
-I {} 指定替換字符串,對(duì)于每一個(gè)命令參數(shù),字符串{}都會(huì)被從stdin讀取到的參數(shù)替換掉,
使用-I的時(shí)候,命令以循環(huán)的方式執(zhí)行,如果有4個(gè)參數(shù),那么命令就會(huì)連同{}一起被執(zhí)行4次,在每一次執(zhí)行中{}都會(huì)被替換為相應(yīng)的參數(shù)。
三、結(jié)合find使用
xargs和find是一對(duì)非常好的組合,但是,我們通常是以一種錯(cuò)誤的方式運(yùn)用它們的,比如:
[root@host1 test]# find . -type f -name "*.txt" -print | xargs rm -f
這樣做是有危險(xiǎn)的,有時(shí)會(huì)刪除不必刪除的文件,如果文件名里包含有空格符(' '),則xargs很可能認(rèn)為它們是定界符(例如,file text.txt會(huì)被xargs誤認(rèn)為file和text.txt)。
如果我們想把find的輸出作為xargs的輸入,就必須將-print0與find結(jié)合使用以字符null('\0')來(lái)分隔輸出,用find找出所有.txt的文件,然后用xargs將這些文件刪除:
[root@host1 test]# find . -type f -name "*.txt" -print0 | xargs -0 rm -f
這樣就可以刪除所有的.txt文件了,xargs -0
將\0作為輸入定界符。
四、運(yùn)用while語(yǔ)句和子shell
[root@host1 test]# cat files.txt | (while read arg ;do cat $arg;done)
這條命令等同于:
[root@host1 test]# cat files.txt | xargs -I {} cat {}
在while循環(huán)中,可以將cat $arg
替換成任意數(shù)量的命令,這樣我們就可以對(duì)同一個(gè)參數(shù)執(zhí)行多條命令,也可以不借助管道,將輸出傳遞給其他命令,這個(gè)技巧適應(yīng)于多種問(wèn)題場(chǎng)景。子shell操作符內(nèi)部的多個(gè)命令可作為一個(gè)整體來(lái)運(yùn)行。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)本站的支持。
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。