如何传递"one"参数并在"xargs"命令中使用它两次

spr*_* cc 8 bash shell popen xargs echo

我试图使用xargs传递参数echo:

[usr@linux scripts]$ echo {0..4} | xargs -n 1 echo
0
1
2
3
4
Run Code Online (Sandbox Code Playgroud)

-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
Run Code Online (Sandbox Code Playgroud)

-n 1当我添加时,似乎禁用了-I@,这是我想要的结果:

0,0
1,1
2,2
3,3
4,4
Run Code Online (Sandbox Code Playgroud)

我怎么能实现这一目标?

--------供应------------------我使用了@ 123推荐的方法,但还有另外一个问题:

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
Run Code Online (Sandbox Code Playgroud)

这是输出:

[usr@linux scripts]$ sh test.sh 
a[0] and a[1] : 1, 2
0,1,0
1,1,1
Run Code Online (Sandbox Code Playgroud)

你可以看到数组a没有返回我想要的值:<我如何解决这个问题?

use*_*001 8

如果无法更改输入格式,可以将分隔符设置为空格:

$ echo -n {0..4} | xargs -d " " -I@ echo @,@
0,0
1,1
2,2
3,3
4,4
Run Code Online (Sandbox Code Playgroud)

否则,更改输入以使用换行符分隔标记:

$ printf "%s\n" {0..4} | xargs -I@ echo @,@
0,0
1,1
2,2
3,3
4,4
Run Code Online (Sandbox Code Playgroud)

这种语法的原因在中解释 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.
Run Code Online (Sandbox Code Playgroud)

因此,如果要分隔字段,则必须手动将分隔符设置为空格.

  • 在`-I`&gt;`下,不加引号的空格不会终止输入项;相反,分隔符是换行符。` (2认同)
  • @springcc 您遇到了一个众所周知的问题。您不能使用 `xagrs -I` 替换作为数组迭代器。所以你需要通过 `eval` 调用一些子 shell,或者只使用 `bash -c`。所以你需要导出你的数组,但是......你不能在 bash 中导出一个数组 :) 从手册页:`数组变量可能(还)不会被导出。`事实上,有一些黑客可以做到这一点,但更好的方法是调整脚本的逻辑,只为 xargs 提供常用变量。 (2认同)