开发者

can xargs separate parameters?

echo "'param 1' 'param 2'" | xargs -n2 -I@ echo [@] [@]

This command outputs:

[param 1 param 2] [param 1 param 2]

However, I would like it to output:

[param 1] [param 2]

Is there a way to do this with xargs? I plan to use this with -L1 so the solution would handle multiple lines as well as multiple argumen开发者_开发知识库ts.


For those who find this from a search, the accepted answer did not work for me.

echo "'param 1' 'param 2'" | xargs -n1 | xargs -I@ echo \[@\] \[@\]

produces:

[param 1] [param 1]
[param 2] [param 2]

which does not meet the requirements given by the original poster to have xargs read in multiple entities, separate them, and send them to a single command ("echo" in the OP) as separate parameters. Xargs is not designed for this sort of task!


The bash answer can work.

p=(`echo "param1 param2"`); echo [${p[0]}] [${p[1]}]

produces:

[param1] [param2]

but this solution does not work with more than one line.


A correct solution with bash for sending pairs of lines as arguments to a single command is:

(echo 'param 1'; echo 'param 2'; echo 'param 3'; echo 'param 4') | while read line1; read line2; do echo "[$line1] [$line2]"; done

produces:

[param 1] [param 2]
[param 3] [param 4]


The GNU Parallel answer does work, but GNU Parallel must be make'd and installed. (The version packaged with Ubuntu is not GNU Parallel.)


echo "'param 1' 'param 2'" | xargs -n1 | xargs -I@ echo \[@\] \[@\]

(In my shell I need to escape [], your mileage may vary).


why stick xargs? bash could handle this well:

p=(`echo "param1 param2"`); echo ${p[0]} ${p[1]}


With GNU Parallel you can do:

(echo 'param 1'; echo 'param 2') | parallel -N2 echo '\[{1}] \[{2}]'

Watch the intro video to learn more: http://www.youtube.com/watch?v=OpaiGYxkSuQ


As suggested in this answer, given one echo:

param1 param2

param 3 param4

The following pipe:

... | while read line1; read line2; do echo "[$line1] [$line2]"; done

produces:

[param1] [param2]
[param3] [param4]

If you have a file myFile.txt containing many lines with two parameters on each, use the following strategy based on xargs in order to reuse the arguments as $f and $g:

cat myFile.txt | xargs -n1 | while read f; read g; do echo $f $g; done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜