Modifying ini files using shell script

隐身守侯 提交于 2019-12-06 03:36:05

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/19567275/modifying-ini-files-using-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!