使用 sed 和 regex 替换配置文件的部分

Use sed and regex to replace sections of a configuration file

我的配置文件结构如下:

[section1]
path = <path1>
read only = yes
guest ok = yes

[section2]
path = <path2>
read only = no
guest ok = yes

我需要能够使用 sed 命令将配置文件的整个部分 替换为一个新部分。 我想要实现的目标示例:

sudo sed -E -i ':a;N;$!ba;\[section1\]<regex_match_until_end_of_section1>/<new_section_1>/' <config_path>

预期结果:

<new_section_1>

[section2]
path = <path2>
read only = no
guest ok = yes
sudo sed -E -i ':a;N;$!ba;\[section2\]<regex_match_until_end_of_section2>/<new_section_2>/' <config_path>

预期结果:

[section1]
path = <path1>
read only = yes
guest ok = yes

<new_section_2>

虽然 sed 可以做到这一点,但使用 awk 更加直观和干净:

awk -v s='[section1]' -v RS= ' == s {[=10=] = "<new_section_1>"}
{ORS=RT} 1' file

<new_section_1>

[section2]
path = <path2>
read only = no
guest ok = yes

或者:

awk -v s='[section2]' -v RS= ' == s {[=11=] = "<new_section_2>"} 
{ORS=RT} 1' file

[section1]
path = <path1>
read only = yes
guest ok = yes

<new_section_2>

仅使用您显示的示例(考虑到在完整的部分之间您没有新行,但您的部分由新行分隔)请尝试遵循 awk 代码,使用 GNU [编写和测试=11=] 应该适用于任何 awk。其中 s1awk 变量,它具有要比较的值(对于部分)并且 s2 包含新值。

awk -v s1='[section1]' -v s2='<new_section_1>' '
[=10=]~/^\[/{
  val=found=""
  if([=10=]==s1){ found=1   }
}
!NF{
  if(!found){ print val }
  else      { print s2  }
}
{
  val=(val?val ORS:"")[=10=]
}
!NF
END{
  if(!found){ print val }
}
'  Input_file