xargs -I 行為

xargs -I 行為

一個變數var包含多個參數,每個參數由一個新行分隔。

echo "$var" | xargs -I % echo ABC %
#Results in:
#ABC One
#ABC Two
#ABC Three

但是,當省略-I%字元時,我得到以下結果:

echo "$var" | xargs echo ABC
#Results in:
#ABC One Two Three

我曾經讀過 {} 會替換當前參數(就像 find 一樣),但這並沒有發生。我究竟做錯了什麼?

答案1

通常的行為是xargs將盡可能多的參數貼到它運行的任何命令的命令列上,迭代直到完成所有參數。以這種方式使用時,它可以解決命令列長度限制的問題。

但是當您指定-I選項時,它會對每個參數執行命令單獨地, 一次一個。我認為這在 Linux 選項的文檔中並不完全明顯,xargs -I但這就是他們的意思。

-I replace-str
       Replace occurrences of replace-str in the initial-arguments with
       names read from standard input.  Also, unquoted  blanks  do  not
       terminate  input  items;  instead  the  separator is the newline
       character.  Implies -x and -L 1.

答案2

如果您使用 GNU Parallel 而不是 xargs,您可以控制您想要的行為:

# 1 line at a time
echo "$var" | parallel echo ABC {}
# Many lines at a time (divided by # cpu)
echo "$var" | parallel -X echo ABC {} 
# Many lines at a time (not divided)
echo "$var" | parallel -Xj1 echo ABC {} 

安裝 GNU Parallel 只需要 10 秒:

wget pi.dk/3 -qO - | sh -x

觀看介紹影片以了解更多資訊:https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

相關內容