Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying ini files using shell script

Tags:

shell

ini

I have an ini file similar to this

[test]
foo=bar

and if we call this ini file as test1.ini

How do I change the value of foo to foobarbaz for example using shell script.

I have tried the following and it doesn't work for me. I don't see the updated changes in the ini file. how do I write it?

sed "/^foo=/s/=.*/=foobarbaz/" < test1.ini

Do you have any other suggestions

like image 209
pistal Avatar asked Oct 24 '13 13:10

pistal


2 Answers

I personally use a more elaborated sed command, as the same option might appear in several different sections:

sh$ sed -i.bak '/^\[test]/,/^\[/{s/^foo[[:space:]]*=.*/foo = foobarbaz/}' test1.ini
#       ^^^^^^  ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#    make a       in the right         perform the substitution
#   *backup*       section                as you want

And as a safety net, I would add:

sh$ diff test1.ini{,.bak}
2c2
< foo = foobarbaz
---
> foo=bar
like image 55
Sylvain Leroux Avatar answered Oct 27 '22 06:10

Sylvain Leroux


To have the file updated, use the -i option of sed:

sed -i "/^foo=/s/=.*/=foobarbaz/" test1.ini

From man sed:

-i[SUFFIX], --in-place[=SUFFIX]

edit files in place (makes backup if SUFFIX supplied)

So you can also do

sed -i.bak "/^foo=/s/=.*/=foobarbaz/" test1.ini
like image 40
fedorqui 'SO stop harming' Avatar answered Oct 27 '22 06:10

fedorqui 'SO stop harming'