Sed 正则表达式在 yaml 和注释行中查找字符串,保留缩进

问题描述 投票:0回答:1

假设我有以下 yaml:

parent:
  A:
    name: foo
    value: x.y.z # check=something
    # value: "yay" # check=nothing

  B:
    name: bar
    value: p.q.r # check=something
    # value: "yay" # check=nothing

请注意 A.value 和 B.value 行中具有“check=nothing”字符串的“#”位于格式化缩进内,而不是位于文件中行的开头。

情况 1:在某些情况下,我想取消注释所有包含“check=nothing”字符串的行,但也保留缩进。所以输出应该如下所示:

parent:
  A:
   ...
   value: "yay" # check=nothing

  B:
   ...
   value: "yay" # check=nothing

我尝试了下面的正则表达式,这会删除注释,但不会保留缩进:

'/check=something/s/^[ \t]*# //g'

情况 2:在某些情况下,我想注释其中包含“check=something”字符串的行,如下面的输出:

parent:
  A:
    name: foo
    # value: x.y.z # check=something
    ...
  
  B:
    name: bar
    # value: p.q.r # check=something
    ...

我已经尝试了下面的正则表达式,它有评论,但它不保留缩进:

'/type=dotdev/ s/^[ \t]*#*/# /g'

因此实际上,根据其他逻辑,此 yaml 中只有

value:*
行之一适用,但我必须使用
check=*
来执行相关的 sed 正则表达式。

我也尝试过以下正则表达式。这是可行的,但“#”的位置或“#”的期望位于行的开头(而不是缩进的“#”),最终看起来很难看。

'/check=something/ s/^#*/#/g' --> For commenting. This adds '#' to the beginning of the line

'/check=nothing/^#//g' --> For uncommenting, but expects the "#" to be at the beginning of the line.

我的 sed 正则表达式中缺少什么才能保留缩进?

regex unix sed
1个回答
0
投票

它不适用于

sed
,因为它不支持正则表达式中的前瞻(
(?=...)
部分)。

一个选项可能是使用

gawk
,它也可以进行 就地更新

gawk -i inplace '{ if($0 ~ /# check=nothing/){ sub(/# /,""); print $0 } else { print $0 }}' test.yaml
© www.soinside.com 2019 - 2024. All rights reserved.