Use sed and regex to replace sections of a configuration file

Viewed 79

I have a configuration file structured as follows:

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

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

I would need to be able to replace a whole section of the configuration file with a new section using the sed command. Example of what I would like to achieve:

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

Expected result:

<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>

Expected result:

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

<new_section_2>
2 Answers

While sed may be able to do this but using awk is much more intuitive and clean:

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

<new_section_1>

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

Or:

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

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

<new_section_2>

With your shown samples only(considering that in between a complete section you don't have new lines but your sections are separated by new lines) please try following awk code, written and tested with GNU awk should work in any awk. Where s1 is awk variable which has value to be compared(for section) and s2 is containing new value in it.

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