[英]How can i create a Linux Script (bash, sed, awk…) to add a line in a specific section of a configuration's file
I need make a script with Linux common tools (Bash, awk, sed,...) to edit a configuration file in a style like INI, that is: 我需要使用Linux常用工具(Bash,awk,sed等)制作脚本,以使用INI之类的样式来编辑配置文件,即:
[sectionA]
var1=x
var2=y
#...
[sectionB]
var1=x
var2=y
#...
[sectionC]
var1=x
var2=y
#...
I need add a line in a specific section, that is, find a part that start with a line "[sectionX]" and append a line BEFORE the next new line or EOF. 我需要在特定部分中添加一行,即找到一个以“ [sectionX]”行开头的零件,并在下一个新行或EOF之前添加一行。 How can I do this?
我怎样才能做到这一点?
sed -i '/^\[sectionB\]/a\append your line here' my_file
or 要么
sed -i '/^\[sectionB\]/s/$/\nappend your line here/' my_file
example appending a line to [sectionB]
using either command line above 示例,使用上述任一命令行在
[sectionB]
后面添加一行
the output 输出
[sectionA]
var1=x
var2=y
#...
[sectionB]
append your line here
var1=x
var2=y
#...
[sectionC]
var1=x
var2=y
#...
sed -e 's/\(\[sectionB\]\)/\1\nvar_new=value/' -i file.ini
请注意,如果file.ini
已经有定义var_new=something_else
的行,则需要单独删除它。
You can do this with gnu awk
你可以用
gnu awk
做到这一点
awk -vRS= -vORS="\n\n" -F"\n" -vOFS="\n" '/sectionB/ {$1=$1"\nnew=42"}1' file
[sectionA]
var1=x
var2=y
#...
[sectionB]
new=42
var1=x
var2=y
#...
[sectionC]
var1=x
var2=y
#...
Search for sectionB
then add new=42
in that section. 搜索
sectionB
然后添加new=42
在这一节。
您可以使用crudini更加健壮/轻松地编辑文件
crudini --set file 'sectionB' new 42
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.