I need make a script with Linux common tools (Bash, awk, sed,...) to edit a configuration file in a style like INI, that is:
[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. 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
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
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.
您可以使用crudini更加健壮/轻松地编辑文件
crudini --set file 'sectionB' new 42
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.