首页 > 解决方案 > 无法用两个字符之间的空白替换所有内容

问题描述

我正在尝试提取 AWS ARN 字符串的“堆栈名称”部分。字符串如下所示:

arn:aws:cloudformation:ap-southeast-2:111111111111:stack/infrastructure-dev/aaaaaaaa-f005-11e9-9e45-02bf7f1fc1f4

问题与其说是提取,不如说是使用 jq 用修改后的原始值替换原始键。

我的陈述如下:

aws cloudformation list-exports --no-paginate | jq -r '.Exports |= map(if .ExportingStackId != "" then .ExportingStackId |= sub("(?<=\/)(.*?)(?=\/)"; "") else . end)'

sub("(?<=\/)(.*?)(?=\/)"; "")命令将匹配,但它会将字符串的部分替换为空。

{
  "Exports": [
    {
      "ExportingStackId": "arn:aws:cloudformation:ap-southeast-2:111111111111:stack//aaaaaaaa-f005-11e9-bbbb-aaaaaaaa",
      "Name": "BootstrapRoleArn",
      "Value": "arn:aws:iam::111111111111:role/deployment-role"
    },
    {
      "ExportingStackId": "arn:aws:cloudformation:ap-southeast-2:111111111111:stack//aaaaaaaa-f005-11e9-bbbb-aaaaaaaa",
      "Name": "PrivateSubnetAId",
      "Value": "subnet-44444444444"
    },
    ...
    ...
    ...
  ]
}

我需要相反的情况,即围绕字符串的该端口的所有其他内容都设置为空

{
  "Exports": [
    {
      "ExportingStackId": "infrastructure-dev",
      "Name": "BootstrapRoleArn",
      "Value": "arn:aws:iam::111111111111:role/deployment-role"
    },
    {
      "ExportingStackId": "infrastructure-prod",
      "Name": "PrivateSubnetAId",
      "Value": "subnet-44444444444"
    },
    ...
    ...
    ...
  ]
}

作为一个“额外的挑战”,我真的希望能够删除“-dev”或“-prod”的附加部分,这样输出将是:

{
  "Exports": [
    {
      "ExportingStackId": "infrastructure",
      "Name": "BootstrapRoleArn",
      "Value": "arn:aws:iam::111111111111:role/deployment-role"
    },
    {
      "ExportingStackId": "infrastructure",
      "Name": "PrivateSubnetAId",
      "Value": "subnet-44444444444"
    },
    ...
    ...
    ...
  ]
}

标签: regexbashjqgsub

解决方案


而不是 using sub,请考虑使用capture,例如:

(capture(".*(?<x>(?<=\/)(.*?)(?=\/)).*"; "") | .x)

关于删除 -dev 或 -prod 后缀的要求不是很清楚,但您可能想考虑简单地使用sub("-(dev|prod)$"; ""),这样您最终会得到:

.Exports
  |= map(if .ExportingStackId != ""
     then .ExportingStackId 
            |= (capture(".*(?<x>(?<=\/)(.*?)(?=\/)).*"; "")
                | .x 
                | gsub("-(dev|prod)$"; ""))
     else . end)

推荐阅读