2

I have a file which have several sections, I have to change the values of all parameters in section [Test2].

Input:

[Test_1]
abc=123
def=456
.
.
.
so on

[Test_2]
abc=123
def=456
.
.
.
so on

[Test_3]
abc=123
def=456
.
.
.
so on

Expected output:

[Test_1]
abc=123
def=456
.
.
.
so on

[Test_2]
abc=111
def=222
.
.
.
so on

[Test_3]
abc=123
def=456
.
.
.
so on

I tried this:

sed "/\[Test_2\]/{n;s/^\(abc=\).*/\1$val1/';}" input > output.new && mv output.new input
sed "/\[Test_2\]/{n;s/^\(def=\).*/\1$val2/';}" input > output.new && mv output.new input

Where $val1=111 and $val2=222.

But I am not getting expected output. Can anyone help on this?

3

Another approach would be to use Ansible. Your file is an ini_file file format and Ansible manage this kind of file very well.

Check http://docs.ansible.com/ansible/ini_file_module.html

The syntax is very simple, in your example :

- ini_file: dest=/anotherconf
            section=Test_2
            option=abc
            value=111
  • I put this - ini_file: dest=/path-to-file section=Test_2 option=abc value=111 inside one function in bash script. But it said - ini_file: command not found. I am on SunOS. – serenesat Nov 30 '16 at 14:20
0

This worked for me --

sed  '/Test_2/ {n;s/^\(abc=\).*$/\1'"$val1"'/;x;n;s/^\(def=\).*$/\1'"$val2"'/;H;g}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.