使用bash在ini文件更新变种 [英] Update var in ini file using bash

查看:118
本文介绍了使用bash在ini文件更新变种的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个bash脚本来配置服务器的各个方面。这里的上下文中替换conf文件(INI格式)与另一值的变量的值。

I am attempting to write a bash script to configure various aspects of a server. The context here is replacing a value of a variable in a conf file (ini format) with another value.

上下文是

[ssh-iptables]

enabled = false

和我只是需要改变假为真。

And I simply need to change false to true.

通常我只是做与 SED

sed -i 's/^enabled = false/enabled = true/g' /etc/fail2ban/jail.conf

启用=假存在于多个地方。

我已经使用 AWK 没有成功尝试

I've tried using awk with no success

awk -F ":| " -v v1="true" -v opt="enabled" '$1 == "[ssh-iptables]" && !f {f=1}f && $1 == opt{sub("=.*","= "v1);f=0}1' /etc/fail2ban/jail.conf

以上是从这个论坛主题来源,但我真的没有如何使用足够的认识它在脚本,使其工作。所有这似乎做的是猫/etc/fail2ban/jail.conf相当于

The above was sourced from this forum thread but I don't really have enough understanding of how to use it in scripts to make it work. All it seems to do is the equivalent of cat /etc/fail2ban/jail.conf

我已经找到了一些其他的脚本这是相当长这是不理想的,因为这会发生的INI文件加载所以我希望有人能帮助我纠正上述code或点我在正确的方向。

I have found a few other scripts which are considerably longer which isn't ideal as this will happen to loads of ini files so I'm hoping someone can help me correct the above code or point me in the right direction.

道歉,如果这属于上ServerFault,但因为它的脚本,而不是服务器配置本身我想这里可能是更容易的复杂性。

Apologies if this belongs on ServerFault, but as it's scripting rather than the intricacies of server configuration itself I figured here might be more apt.

推荐答案

假设你的格式是没有方括号线(如 [SSH-iptables的] )部分中,我会用你上面的解决方案(以 SED ),但像这样的块中限制查询:

Assuming your format is that there are no square-bracket lines (like [ssh-iptables]) within sections, I would use your solution above (with sed) but restrict the query to within that block like so:

sed -i '/^\[ssh-iptables\]$/,/^\[/ s/^enabled = false/enabled = true/' /etc/fail2ban/jail.conf

一开始的额外部分告诉下面的替代语句仅是线之间运行 [SSH-iptables的] 和以<$开始下一个C $ C> [。它采用用逗号分隔的两个常规的前pressions这表明了界限。

The extra part at the beginning tells the following substitution statement to only run between the line that is [ssh-iptables] and the next one that starts with a [. It uses two regular expressions separated by a comma which indicate the bounds.

这篇关于使用bash在ini文件更新变种的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆