bash 使用 xargs 将行拆分为 3 个单独的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29720413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split line into 3 separate arguments using xargs
提问by brucezepplin
If I have the following:
如果我有以下几点:
$ printf '%s\n' "${fa[@]}"
1 2 3
4 5 6
7 8 9
where each line is a new array element. I want to be able to split the element by space delimiter and use the result as 3 separate parameters and pipe into xargs.
其中每一行都是一个新的数组元素。我希望能够通过空格分隔符分割元素,并将结果用作 3 个单独的参数并通过管道输入 xargs。
For example the first element is:
例如第一个元素是:
1 2 3
where using xargs I want to pass 1
, 2
and 3
into a simple echo command such as:
使用 xargs 我想传递1
,2
并3
进入一个简单的 echo 命令,例如:
$ echo printf '%s\n' "${fa[@]}" | cut -d' ' -f1,2,3 | xargs -d' ' -n 3 bash -c 'echo 1
2
3 4
5
6 7
8
9 10
'
1
4
7
$ echo
2
5
8
$ echo
3
9
6
So I have been trying doing this in the following way:
所以我一直在尝试通过以下方式做到这一点:
$ echo fa=('1 2 3' '4 5 6' '7 8 9')
1
4
7
which gives:
这使:
printf '%s\n' "${fa[@]}" | xargs -n 3 sh -c 'echo call_my_command --arg1="" --arg2="" --arg3=""' argv0
which aside from the strange line ordering - trying xargs -d' ' -n 3 bash -c 'echo $0'
does not print out the first "element" of each line i.e.
除了奇怪的行排序 - 尝试xargs -d' ' -n 3 bash -c 'echo $0'
不会打印出每行的第一个“元素”,即
call_my_command --arg1=1 --arg2=2 --arg3=3
call_my_command --arg1=4 --arg2=5 --arg3=6
call_my_command --arg1=7 --arg2=8 --arg3=9
but rather prints them all out.
而是将它们全部打印出来。
What I am asking is, for each element, how do I split the line into three separate arguments that can be referenced via xargs?
我要问的是,对于每个元素,如何将行拆分为三个可以通过 xargs 引用的独立参数?
Thanks!
谢谢!
回答by Tim Rijavec
You were going in the right direction
你正朝着正确的方向前进
To declare an array:
声明一个数组:
printf '%s\n' "${fa[@]}" | cut -d' ' -f1,2,3 | xargs -n 3 bash -c 'echo ##代码## '
To achieve what you want:
为了实现你想要的:
##代码##this will echo you the following lines (change command that is passed to the xargs accordingly)
这将回显以下几行(相应地更改传递给 xargs 的命令)
##代码##If I just add your answer and changed it a little we'll get the following
如果我只是添加您的答案并稍作更改,我们将得到以下结果
##代码##notice missing -d' ' in xargs, this option is not available in some versions of xargs.
注意 xargs 中缺少 -d' ',此选项在某些版本的 xargs 中不可用。