我尝试使用 xargs
将参数传递给 echo
:
[usr@linux scripts]$ echo {0..4} | xargs -n 1 echo
0
1
2
3
4
-n 1
确保 xargs
一次将 1
个参数传递给 echo
。
然后我想使用这个参数两次,但是结果不是我想要的:
[usr@linux scripts]$ echo {0..4} | xargs -I@ -n 1 echo @,@
0 1 2 3 4,0 1 2 3 4
当我添加 -I@
时,-n 1
似乎已禁用,
这就是我想要的结果:
0,0
1,1
2,2
3,3
4,4
我怎样才能做到这一点?
--------供给---------------- 我使用了@123推荐的方法,但是还有一个问题:
测试.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
这是输出:
[usr@linux scripts]$ sh test.sh
a[0] and a[1] : 1, 2
0,1,0
1,1,1
你可以看到数组 a
没有返回我想要的值:<
我该如何解决这个问题?
最佳答案
如果你不能改变输入格式,你可以设置分隔符为空格:
$ echo -n {0..4} | xargs -d " " -I@ echo @,@
0,0
1,1
2,2
3,3
4,4
否则,更改输入以用换行符分隔标记:
$ printf "%s\n" {0..4} | xargs -I@ echo @,@
0,0
1,1
2,2
3,3
4,4
这种语法的原因在 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.
因此,如果要分隔字段,则必须手动将分隔符设置为空格。
关于bash - 如何传递 "one"参数并在 "xargs"命令中使用它两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40126356/