gpt4 book ai didi

bash - sed 模式在字符后插入逗号

转载 作者:行者123 更新时间:2023-12-02 19:13:32 24 4
gpt4 key购买 nike

使用 bash 在右括号 } 后添加逗号。

使用

sed 's/variable/&,/g;s/,$//'

变量之后添加逗号,但是,

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
}

最佳答案

在大括号后添加逗号,但不在最后一行:

sed -e '$!s/^ \{4\}}$/&,/'
  • $!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
}

更复杂:在每行添加逗号,但不在每个 block 的最后添加逗号:

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
}
  • :a; 标签 "a" 表示进一步分支
  • N; 与下一行合并
  • /[^{\[(,] *\n/ 如果缓冲区包含逗号或开括号以外的内容,则后跟换行符
  • { 然后执行阻止:
    • /\n[\o11]*[]})]/! 如果缓冲区不包含换行符,后跟空格和其他则关闭括号
    • s/\n/,\n/ 然后在换行符之前放置一个逗号
    • }; block 结束
  • P; 打印缓冲区最多换行
  • D; 删除缓冲区直至换行符
  • $!ba 如果不在最后一行,则分支到 "a"

关于bash - sed 模式在字符后插入逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63949362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com