Bash sed模式在字符后插入逗号
使用bash在结束括号Bash sed模式在字符后插入逗号,bash,sed,Bash,Sed,使用bash在结束括号}后添加逗号 使用 但是,在变量后添加逗号 sed 's/}/&,/g;s/,$//' 不起作用 输入: variable "policy_name1" { description = "abc xyz" type = string default = [ "test1" "test2" ]
}
后添加逗号
使用
但是,在变量后添加逗号
sed 's/}/&,/g;s/,$//'
不起作用
输入:
variable "policy_name1" {
description = "abc xyz"
type = string
default = [
"test1"
"test2"
]
}
variable "policy_name2" {
description = "abc xyz"
type = bool
default = false
}
输出:
variable "policy_name1" {
description = "abc xyz"
type = string
default = [
"test1"
"test2"
]
},
variable "policy_name2" {
description = "abc xyz"
type = bool
default = false
}
这是你能做的
#!/usr/bin/env bash
FILENAME="test.tf"
COUNT=`wc -l $FILENAME | awk '{ print $1 }'`
COUNT=`expr $COUNT - 1`
sed "1,$COUNT s/}/},/" "$FILENAME"
我提供了一个bash脚本,这样我们就可以以正确的方式避免最后一行。此脚本在找到结束的花括号(})时将附加逗号,但在最后一行时除外。在花括号后添加逗号,但不在最后一行:
不在最后一行替换$!s/
行以4个空格开头,后跟^\{4\}$
}
按匹配的内容,然后是/&,/
,
variable "policy_name1" {
description = "abc xyz"
type = array
default = [
"test1"
"test2"
]
},
variable "policy_name2" {
description = "abc xyz"
type = bool
default = false
},
variable "policy_name3" {
description = "simple test string..."
type = int
default = 42
}
更复杂:在每行上添加逗号,但不在每个块的最后添加逗号:
可以呈现:
variable "policy_name1" {
description = "abc xyz",
type = array,
default = [
"test1",
"test2"
]
},
variable "policy_name2" {
description = "abc xyz",
type = bool,
default = false
},
variable "policy_name3" {
description = "simple test string...",
type = int,
default = 42
}
:a代码>标签
用于进一步分支“a”
N代码>与下一行合并
如果缓冲区包含逗号或开括号以外的内容,后跟换行符/[^{\[(,]*\n/
然后执行块:{
如果不是缓冲区,则包含换行符,后跟空格和其他,然后关闭括号/\n[\o11]*[]}]/!
然后在换行符前加逗号s/\n/,\n/
}代码>块结束
P代码>打印缓冲区到换行符
D代码>删除缓冲区直到换行
如果不在最后一行,则转到$!ba
“a”
sed s/}/},/test.tf
上述命令将简单地用结束的花括号和逗号(},)@F.Hauri Right,我想的是sed-E
/sed-r
行为!您已经打开了一个包含相同示例文件的问题,并且希望对其进行分析并提取值。以防您认为必须为解析准备此文件(我认为这是一个好主意),在其中添加逗号似乎没有帮助。
variable "policy_name1" {
description = "abc xyz"
type = array
default = [
"test1"
"test2"
]
},
variable "policy_name2" {
description = "abc xyz"
type = bool
default = false
},
variable "policy_name3" {
description = "simple test string..."
type = int
default = 42
}
sed -e ':a;N;/[^{\[(,] *\n/{/\n[ \o11]*[]})]/!s/\n/,\n/};P;D;$!ba'
variable "policy_name1" {
description = "abc xyz",
type = array,
default = [
"test1",
"test2"
]
},
variable "policy_name2" {
description = "abc xyz",
type = bool,
default = false
},
variable "policy_name3" {
description = "simple test string...",
type = int,
default = 42
}