简体   繁体   English

我如何创建Linux脚本(bash,sed,awk…)在配置文件的特定部分添加一行

[英]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.

相关问题 如何在Linux Bash脚本文件中使用'sed'注释掉带有制表符间距的特定行? - How can I use 'sed' in a Linux Bash script file to comment out a particular line with tabbed spacing? 使用 awk 或 sed 将文件中的特定行或多行移动到其他行的 Bash 脚本? - Bash script to move specific line or lines in a file to other line with awk or sed? 如何使用 sed 或 awk 写入特定的行范围? - How can I write to a specific line range with sed or awk? 如何使用 bash 脚本在文件中的特定单词或行后添加一行? - How can i add a block of line after a specific word or line in a file using bash script? 如何使用awk / sed在2行之间添加新行文本? (在文件中) - How can I add a new line of text between 2 lines using awk/sed? (in a file) 如果该行包含sed / awk或bash的特定单词,同时又保持白色间距,如何更改列中的值? - How can I change a value in a column if that line contains a specific word using sed/awk or bash while keeping the whitespacing? 如何使用cat,sed,awk或cut将列添加到csv文件中的特定位置? - How can I add a column to a specific position in a csv file using cat, sed, awk or cut? 如何将linux bash脚本文件添加到terraform代码中? - How can i add linux bash script file into terraform code? 如何在 bash 命令行或脚本中位置更改的文件中替换特定字符? - How can I replace a specific character in a file where it's position changes in bash command line or script? 如何替换bash脚本中文件的特定行? - How can I replace a specific line of a file in bash script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM