【问题标题】:unable to replace everything with empty between two characters无法在两个字符之间用空替换所有内容
【发布时间】:2019-10-17 03:12:31
【问题描述】:

我正在尝试提取 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("(?&lt;=\/)(.*?)(?=\/)"; "") 命令将匹配,但会将字符串的部分替换为空。

{
  "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"
    },
    ...
    ...
    ...
  ]
}

【问题讨论】:

    标签: regex bash jq gsub


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 难以置信。像魅力一样工作。我的正则表达式技能低于标准 - 在这种情况下会做什么,因为您将它传递给 | .x ?
    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多