Xargs按空间拆分字符串
我有以下shell脚本:
serial_numbers=$(ddcutil detect | grep "Serial number" | awk '{print $3}' | uniq)
echo $serial_numbers | xargs -P $(echo $serial_numbers | wc -w) -I % ddcutil setvcp 10 100 --sn %
变量$ serial_number
包含字符串'8trnjq2 fgvf2y2'
。 XARGS
将此字符串解释为一个单个参数,仅产生一个调用ddcutil setVcp
。但是我希望xargs
在空间上拆分字符串,因此我将两个调用带有8trnjq2
和fgvf2y2
作为参数。
编辑:使用-t''
为字符串中的最后一部分提供了奇怪的结果:'fgvf2y2'$'\ n'\ n'
I have the following shell script:
serial_numbers=$(ddcutil detect | grep "Serial number" | awk '{print $3}' | uniq)
echo $serial_numbers | xargs -P $(echo $serial_numbers | wc -w) -I % ddcutil setvcp 10 100 --sn %
The variable $serial_number
contains the string '8TRNJQ2 FGVF2Y2'
.xargs
interprets this string as one single argument and produces only one invocation of ddcutil setvcp
. But I want xargs
to split the string at the space, so iÍ get two invocations with 8TRNJQ2
and FGVF2Y2
as arguments.
Edit: using -t ' '
gives me strange results for the last part in the string: 'FGVF2Y2'$'\n'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
XARGS
如果您直接从命令中输送它,则可以正常工作,但是如果您echo
相同命令输出的结果,则可以正常工作。在您的命令中添加此转换:
XARGS
现在将了解您要在序列号上拆分。另外,您可以将
tr
放在第一行中,然后将分离的序列号存储在变量中。xargs
works fine if you pipe it directly from a command, but not if youecho
the result of the same command output.Add this transformation in your command:
xargs
will now understand that you want to split on your serial numbers.Alternatively, you could put the
tr
in your first line and store the separated serial numbers in the variable.XARGS
具有-n
选项,该选项可用于分裂单弦输入。但是我注意到,使用
-i
与-n1
一起破坏了其分裂行为(无引用的空白不终止输入项目 -man xargs
)。因此,除了使用
tr
之外,打破线路的另一种方法是将定界符通过xargs
带有-d
。另外,您需要将
-n
添加到echo
才能删除tawning newline,您将其视为$'\ n'\ n'
(并且它' LL随后的管道中断):或者您可以在管道中插入另一个XARG:
xargs
has-n
option which is someway usable for splitting one-string input.But I noticed, that using
-I
together with-n1
destroys its splitting behavior (unquoted blanks do not terminate input items -man xargs
).So another way to break a line besides using
tr
is explicitly passing delimiter toxargs
with-d
.Also you will need to add
-n
to yourecho
to remove trailing newline, that you see as$'\n'
(and it'll break subsequent piping):or you can just insert another xargs in your pipe: