xargs命令詳解,linuxxargs命令詳解

來源:互聯網
上載者:User

xargs命令詳解,linuxxargs命令詳解

xargs命令是把接收到的資料重新格式化,再將其作為參數提供給其他命令,下面介紹xargs命令的各種提示

一、將多行輸入轉換成單行輸入:

[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

  將單行輸入轉換成多行輸出:

[root@host1 test]# cat example.txt | xargs -n 31 2 34 5 67 8 910 11 12

  自訂定界符進行轉換(預設的定界符是空格):

[root@host1 test]# echo "Hello:Hello:Hello:Hello" | xargs -d : -n 2Hello HelloHello Hello

二、在指令碼中運用:

[root@host1 test]# cat echo.sh #!/bin/bashecho $* '^-^'當參數傳遞給echo.sh後,它會將這些參數列印出來,並且以"^-^"作為結尾:[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 ^-^

  在上面的例子中,我們把參數源都放入args.txt檔案,但是除了這些參數,我們還需要一些固定不變的參數,比如:

[root@host1 test]# bash echo.sh  Welcome Tom Welcome Tom ^-^

  在上述命令執行過程中,Tom是變數,其餘部分為常量,我們可以從"args.txt"中提取參數,並按照下面的方式提供給命令:

[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 {} 指定替換字串,對於每一個命令參數,字串{}都會被從stdin讀取到的參數替換掉,

  使用-I的時候,命令以迴圈的方式執行,如果有4個參數,那麼命令就會連同{}一起被執行4次,在每一次執行中{}都會被替換為相應的參數。

三、結合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結合使用以字元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 {}

  在while迴圈中,可以將cat $arg替換成任意數量的命令,這樣我們就可以對同一個參數執行多條命令,也可以不藉助管道,將輸出傳遞給其他命令,這個技巧適應於多種問題情境。子shell操作符內部的多個命令可作為一個整體來運行。

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.