将 perl 正则表达式捕获组存储在 bash 个变量中

Store perl regex capture groups in bash variables

我正在编写一个小 bash 脚本来通过我们的 api.

获取某些硬件的状态
curl -sG ip:port/device/status -o temp.txt

我使用 curl 命令获取状态并写入临时文件

我试过不同的正则表达式类型,简单的 bash 正则表达式不够用,最终使用了 perl。

perl -nle 'printf("'%-15s' \t '%-15s' \t '%-15s' \t '%-15s' \n", "", "", "", "") while m{regex_to_capture_data}g' temp.txt

我的正则表达式捕获工作正常并完美打印(一些迭代将有空白捕获组,这是重要信息,并且按预期打印)

有没有办法让数组填充这些捕获组并在我的 bash 脚本中进一步使用它们?

例如 $1、$2、$3、$4 是字段 device_id、正常运行时间、状态 last_error。在我的 curl 命令中,我有 4 个设备的信息。我希望 device_id[0] 最多 [device_id[3],并且每个捕获组都相同。

我没有使用 perl 的经验,只是按照一些论坛帖子的建议使用它,因此非常感谢任何关于如何实现这一点的建议。

您的示例代码显然有问题;你不能嵌套单引号;尽管 Perl 提供了方便的操作符 q() 所以你可以很容易地解决这个问题。格式也有其他错误。可能你的意思是

perl -nle 'print(join("\t", "", "", ", ""), "\n") while m{regex_to_capture_data}g' temp.txt

您可以通过管道将其传送至

while IFS=$'\t' read -r boulders rubble stones rocks; do
    ...

尽管您可能也可以 运行 直接从 Perl 执行循环的主体。

perl -nle 'system("geologee", "--boulders", , "--rubbleUrl", ":/") while m{regex_to_capture_data}g' temp.txt