首页 > 解决方案 > 如何为大括号之间的代码匹配正则表达式

问题描述

我需要匹配包含此行的所有块

  role = "${module.iam_basic.ec2_base_instance_role}"

我的文件看起来像这样

module "iam_basic" {
 source = "../../../../modules/aws/iam/ec2"
 base_profile = "staging_srv_profile"
 base_role = "staging_srv_role"
}
resource "aws_iam_role_policy" "s3_bucket_policy" {
name = "s3-policy"
role = "${module.iam_basic.ec2_base_instance_role}"
policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement":[
 {
   "Effect":"Allow",
   "Action":"s3:*",
   "Resource":["arn:aws:s3:::stg-access/*",
              "arn:aws:s3:::stg-access"]

  }
 ]
}
EOF
}

所以正则表达式应该匹配

resource "aws_iam_role_policy" "s3_bucket_policy" {
name = "s3-policy"
role = "${module.iam_basic.ec2_base_instance_role}"
policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement":[
 {
   "Effect":"Allow",
   "Action":"s3:*",
   "Resource":["arn:aws:s3:::stg-access/*",
              "arn:aws:s3:::stg-access"]

  }
 ]
}
EOF
}

我试图创建正则表达式,我想出了这个:

/^(.*?){([^}]*)}/gm

但它不正确匹配,请帮助我,如果您有任何其他方法,例如使用 grep、awk、sed 等工具

标签: bashawksedgrep

解决方案


仅基于您显示的示例,您能否尝试在 GNU 中进行以下、编写和测试awk

awk '
/^module "/{
  if(found){ print val }
  found=""
}
/\<role = "\${module\.iam_basic\.ec2_base_instance_role}"/{
  found=1
}
{
  val=(val?val ORS:"")$0
}
END{
  if(found){ print val }
}' Input_file

说明:为上述添加详细说明。

awk '                        ##Starting awk program from here.
/^module "/{                 ##Checking condition if line starts from module " then do following.
  if(found){ print val }     ##Checking condition if found is SET then print the val.
  found=""                   ##Nullify found here.
}
/^role = "\${module\.iam_basic\.ec2_base_instance_role}"/{ ##Check if line has mentioned pattern in it shown by OP.
  found=1                    ##Set found to 1 here.
}
{
  val=(val?val ORS:"")$0     ##Creating val and keep appending current line values to it.
}
END{                         ##Starting END block of this program from here.
  if(found){ print val }     ##Checking condition if found is SET then print the val.
}' Input_file                ##Mentioning Input_file name here.

推荐阅读