gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:55:06 28 4
gpt4 key购买 nike

我尝试使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com