今天就跟大家聊聊有關(guān)如何在linux中使用xargs命令,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序定制開發(fā)、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了武江免費建站歡迎大家使用!
一、將多行輸入轉(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
自定義定界符進行轉(zhuǎn)換(默認的定界符是空格):
[root@host1 test]# echo "Hello:Hello:Hello:Hello" | xargs -d : -n 2 Hello Hello Hello Hello
二、在腳本中運用:
[root@host1 test]# cat echo.sh #!/bin/bash echo $* '^-^'
當參數(shù)傳遞給echo.sh
后,它會將這些參數(shù)打印出來,并且以"^-^"作為結(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í)行過程中,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
這時我們需要使用xargs中-I命令:
[root@host1 test]# cat args.txt | xargs -I {} bash echo.sh Welcome {} Welcome Tom ^-^ Welcome Harry ^-^ Welcome Jerry ^-^ Welcome Lucy ^-^
-I {} 指定替換字符串,對于每一個命令參數(shù),字符串{}都會被從stdin讀取到的參數(shù)替換掉,
使用-I的時候,命令以循環(huán)的方式執(zhí)行,如果有4個參數(shù),那么命令就會連同{}一起被執(zhí)行4次,在每一次執(zhí)行中{}都會被替換為相應(yīng)的參數(shù)。
三、結(jié)合find使用
xargs和find是一對非常好的組合,但是,我們通常是以一種錯誤的方式運用它們的,比如:
[root@host1 test]# find . -type f -name "*.txt" -print | xargs rm -f
這樣做是有危險的,有時會刪除不必刪除的文件,如果文件名里包含有空格符(' '),則xargs很可能認為它們是定界符(例如,file text.txt會被xargs誤認為file和text.txt)。
如果我們想把find的輸出作為xargs的輸入,就必須將-print0與find結(jié)合使用以字符null('\0')來分隔輸出,用find找出所有.txt的文件,然后用xargs將這些文件刪除:
[root@host1 test]# find . -type f -name "*.txt" -print0 | xargs -0 rm -f
這樣就可以刪除所有的.txt文件了,xargs -0
將\0作為輸入定界符。
四、運用while語句和子shell
[root@host1 test]# cat files.txt | (while read arg ;do cat $arg;done)
這條命令等同于:
[root@host1 test]# cat files.txt | xargs -I {} cat {}
看完上述內(nèi)容,你們對如何在linux中使用xargs命令有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
本文題目:如何在linux中使用xargs命令
文章源于:http://jinyejixie.com/article2/iiceic.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、網(wǎng)頁設(shè)計公司、App開發(fā)、用戶體驗、網(wǎng)站制作、ChatGPT
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)