Xargs按空间拆分字符串

发布于 2025-01-28 03:09:09 字数 551 浏览 3 评论 0原文

我有以下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在空间上拆分字符串,因此我将两个调用带有8trnjq2fgvf2y2作为参数。

编辑:使用-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 xargsto 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

同尘 2025-02-04 03:09:09

XARGS如果您直接从命令中输送它,则可以正常工作,但是如果您echo相同命令输出的结果,则可以正常工作。

在您的命令中添加此转换:

#!/bin/bash

echo $serial_numbers | tr ' ' '\n' | xargs -P $(echo $serial_numbers | wc -w) -I % ddcutil setvcp 10 100 --sn %

XARGS现在将了解您要在序列号上拆分。

另外,您可以将tr放在第一行中,然后将分离的序列号存储在变量中。

xargs works fine if you pipe it directly from a command, but not if you echo the result of the same command output.

Add this transformation in your command:

#!/bin/bash

echo $serial_numbers | tr ' ' '\n' | xargs -P $(echo $serial_numbers | wc -w) -I % ddcutil setvcp 10 100 --sn %

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.

三岁铭 2025-02-04 03:09:09

XARGS具有-n选项,该选项可用于分裂单弦输入。
但是我注意到,使用-i-n1一起破坏了其分裂行为(无引用的空白不终止输入项目 - man xargs)。
因此,除了使用tr之外,打破线路的另一种方法是将定界符通过xargs带有-d
另外,您需要将-n添加到echo才能删除tawning newline,您将其视为$'\ n'\ n'(并且它' LL随后的管道中断):

echo -n "a b c" | xargs -d " " -I% echo letter_%

或者您可以在管道中插入另一个XARG:

echo -n "a b c" | xargs -n1 | xargs -I% echo letter_%

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 to xargs with -d.
Also you will need to add -n to your echo to remove trailing newline, that you see as $'\n' (and it'll break subsequent piping):

echo -n "a b c" | xargs -d " " -I% echo letter_%

or you can just insert another xargs in your pipe:

echo -n "a b c" | xargs -n1 | xargs -I% echo letter_%
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文