Simple linux command line command to modify an option in a INI like config file

浪尽此生 提交于 2020-01-01 05:26:19

问题


I am looking for a generic command line solution that would allow me to add or modify a configuration option inside a config file (ini like format).

Most linux configuration files use a INI like format, with # and ; as comment and with option=value.

Mainly I am looking for something that would take filename, option and value, and that will change the config to match this.

I want to use this to write some auto-deployment scripts. I have no problem on using tools that are not installed by default on Debian or Ubuntu as long they do exist in the default distribution repositories (as I can do an apt-get install xxx, if needed).

Example: change-config /etc/default/nginx ULIMIT '"-n 4096"'

The expected result would be to have ULIMIT="-n 4096" inside the nginx file. Obviously if it does already exists and have the same value, it should do nothing. If it exists, commenting the old line would be fine and adding the new one.

As a note, these config files can have spaces/tabs between parameters so if you have ULIMIT = "..." is still the same command. That's why I was looking for something better than sed as there are plenty of corner cases to evaluate.

Also, I don't want to reinvent the wheel, and I doubt that I am the first one to look for a solution to this kind of problem.


回答1:


git config is actually a semi-generic INI interface.

❱ git config --file=/etc/default/nginx somegroup.ULIMIT '-n 4096'
❱ cat /etc/default/nginx
[somegroup]
    ULIMIT = -n 4096
❱ git config --file=/etc/default/nginx somegroup.ULIMIT
"-n 4096"

It doesn't support adding top-level keys, though. All keys have to be placed in an INI style group, hence the "somegroup." above. That makes it unsuitable for your task, but I thought I'd mention it here for others finding their way here.




回答2:


Try crudini. BTW I think this file is a shell file rather than an ini file, but crudini can still work in this case:

crudini --set /etc/default/nginx '' ULIMIT '"-n 4096"'



回答3:


Augeas / augtool aims to do this, although you'll need the right lens for the type of file you're after (you can also write your own), for example, the Nginx lens.

It also has an API if required.



来源:https://stackoverflow.com/questions/22834680/simple-linux-command-line-command-to-modify-an-option-in-a-ini-like-config-file

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