3 ms·
Manage/edit large, complex configuration files with sed and ed
#!/bin/sh
# 1.sh: search/dump
test $# -gt 1||exec echo "usage: $0 cfg-file [section]";
x=$1;shift;y=$(echo "$@"|sed 's/ /./g');sed -En "/$y/=;/./{/$y/,/[^L^K]/p;}" $x
#!/bin/sh
# 2.sh: delete/remove
test $# -gt 2||exec echo "usage: $0 cfg-file section";
x=$1;shift;y=$(echo "$@"|sed 's/ /./g');sed -iE "/./{/$y/,/[^L^K]/d;}" $x
#!/bin/sh
# 3.sh: add/insert
test $# -eq 2||exec echo usage: $0 cfg-file line-no \< section-file
(echo $2;echo a;sed '1{/^[1-9]*/d;}';echo .;echo wq)|ed $1
Objective: Without needing non-standard programs or large scripting laguages, manage and edit long. relatively complex configuration files that are divided into sections.
NB. I wrote this for me, not anyone else. It is shared here only because it demonstrates a stupid sed trick I have never seen anyone else use. I have been using this sed technique for over 10 years.
Example:
# 1.cfg: indented config file
# sections are separated with a left-justified control character such as ^L or ^K
# note for learners: ^L is inserted by typing Ctrl-V followed by Ctrl-L
^L
# SECTION W-a1
foo
^L
# SECTION X-b1
bar
^L
# SECTION Y-c1
baz
^L
# SECTION Z-d1
qux
Dump all sections
1.sh 1.cfg \# SECTION
The line numbers for all lines will be printed. This can be useful for adding/inserting sections. The output can also be edited to work as an ed script.
Dump sections W-a1 and Y-c1
1.sh 1.cfg \# SECTION [WY]-[ac]1
The line number for the section header will be printed. This number, e.g., N-1, can be useful when adding/inserting sections.
Dump section Y-c1 to a file for editing
1.sh 1.cfg \# SECTION Y-c1 > edit.txt
Delete section Y-c1
2.sh 1.cfg \# SECTION Y-c1
Insert edited/new section into config file, in the location previously occupied by section Y-c1 we deleted earlier
3.sh 1.cfg 9 < edit.txt
9 is the line number where we want the section inserted