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