使用 xargs 時重定向到 stdin 而不是參數

使用 xargs 時重定向到 stdin 而不是參數

例如,使用命令

cat foo.txt | xargs -I{} -n 1 -P 1 sh -c "echo {} | echo"

包含foo.txt兩行

foo
bar

上面的命令不列印任何內容。

答案1

cat foo.txt | xargs -J % -n 1 sh -c "echo % | bar.sh" 

棘手的部分是 xargs 執行隱式子 shell 呼叫。這裡 sh 顯式調用,管道不會成為父傳送帶的一部分

答案2

如果您想處理 foo.txt 的所有行,則必須使用循環。用於&將進程置於後台

while read line; do
   echo $line | bar.sh &
done < foo.txt

如果您的輸入包含空格,請暫時將內部欄位分隔符號設定為換行符

# save the field separator
OLD_IFS=$IFS

# new field separator, the end of line 
IFS=$'\n'

for line in $(cat foo.txt) ; do
   echo $line | bar.sh &
done

# restore default field separator  
IFS=$OLD_IFS     

相關內容