bash - 如何为大括号之间的代码匹配正则表达式
问题描述
我需要匹配包含此行的所有块
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 等工具
解决方案
仅基于您显示的示例,您能否尝试在 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.
推荐阅读
- java - ExoPlayer 2.8.2 更改 - TrackSelectionHelper 和选择对话框
- windows - 子进程有时会返回空
- ios - 快速解码Base64图像
- ios - ios - 根据屏幕大小调整按钮的宽度和高度
- windows - 菜鸟问:如何将空文件夹推送到我的 BitBucket git repo
- python - 如何计算 Django 中跨字段的值?
- laravel - 为什么验证消息没有与 required_if 一起出现?
- python - 如何使用 Lmfit 和 Python 解决 NaN 值错误
- javascript - 如何禁用 setInterval 功能并重新启动
- vue.js - 小吃店会在 3 秒后自动关闭。如何在 vue 中关闭小吃店后将状态设置为 false