Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use sed and regex to replcae sections of a configuration file

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading