Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can xargs separate parameters?

Tags:

linux

shell

xargs

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 arguments.

like image 709
jcalfee314 Avatar asked May 23 '11 15:05

jcalfee314


1 Answers

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.)

like image 179
Sarkom Avatar answered Oct 17 '22 08:10

Sarkom