Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass "one" argument and use it twice in "xargs" command

I tried to use the xargs to pass the arguments to the echo:

[usr@linux scripts]$ echo {0..4} | xargs -n 1 echo
0
1
2
3
4

the -n 1 insured that the xargs pass 1 arguments a time to the echo.

Then I want to use this aruments twice, however the results is not I wanted:

[usr@linux scripts]$ echo {0..4} | xargs -I@ -n 1 echo @,@
0 1 2 3 4,0 1 2 3 4

the -n 1 seems disabled when I added the -I@, and this is the result I wanted:

0,0
1,1
2,2
3,3
4,4

how can I achieve that?

--------Supply------------------ I have used the method recommanded by @123 ,however ,there are still another question:

test.sh:

#!/bin/bash
a[0]=1
a[1]=2
echo "a[0] and a[1] : "${a[0]}, ${a[1]}
echo -n {0..1} | xargs -I num -d" " echo num,${a[num]},num

and this is the output:

[usr@linux scripts]$ sh test.sh 
a[0] and a[1] : 1, 2
0,1,0
1,1,1

you can see that the array a is not returned the value I wanted :< And How can I fix this problem?

like image 834
spring cc Avatar asked Oct 19 '16 08:10

spring cc


1 Answers

If you can't change the input format, you could set the delimiter to a space:

$ echo -n {0..4} | xargs -d " " -I@ echo @,@
0,0
1,1
2,2
3,3
4,4

Otherwise, change the input to separate the tokens with a newline:

$ printf "%s\n" {0..4} | xargs -I@ echo @,@
0,0
1,1
2,2
3,3
4,4

The reason for this syntax is explained in man xargs

-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 sep‐
arator is the newline character.  Implies -x and -L 1.

So you must set the delimiter manually to a space if you want to delimit fields.

like image 155
user000001 Avatar answered Oct 21 '22 18:10

user000001