0

I have a config file app.ini (the background is gitea, but that is not important)

[log]
MODE      = file
LEVEL     = info

[server]
SSH_DOMAIN       = localhost
DOMAIN           = localhost
HTTP_PORT        = 3000

[mailer]
ENABLED = false

I would like to add multiple lines at the end of the [server] block via a bash command (without open and edit app.ini). How to add something to the end is clear (echo "xyz" >> app.ini).

The result should be something like:

[log]
MODE      = file
LEVEL     = info

[server]
SSH_DOMAIN       = localhost
DOMAIN           = localhost
HTTP_PORT        = 3000
PROTOCOL = https
CERT_FILE = cert.pem
KEY_FILE = key.pem

[mailer]
ENABLED = false

Adding the new lines below [server] is also fine:

[server]
PROTOCOL = https
CERT_FILE = cert.pem
KEY_FILE = key.pem
...

Thanks in advance.

tom
  • 9,550
  • 6
  • 30
  • 49

2 Answers2

2

With ed and bash.

printf '%s\n' '/^\[server\]/,/^HTTP_PORT[[:space:]]*=.*/a' $'POROTOCOL = https\nCERT_FILE = cert.pem\nKEY_FILE = key.pem' . ,p Q | ed -s app.ini

Or you can save that multiline strings in a separate file, and create an ed script that has the following code.

H
/^\[server\]$/,/^HTTP_PORT[[:space:]]*=.*/r insert.txt
,p
Q
  • Where insert.txt contains your strings to insert and script.ed is the script.

Then

ed -s app.ini < script.ed 
  • Change the Q to w if you think that the output is correct, to edit the app.ini

Without the separate config file, the script looks something like this.

H
/^\[server\]/,/^HTTP_PORT[[:space:]]*=.*/a                           
POROTOCOL = https
CERT_FILE = cert.pem
KEY_FILE = key.pem
.
,p
Q

Then same syntax for calling the script against the file.

ed -s app.ini < script.ed
Jetchisel
  • 7,493
  • 2
  • 19
  • 18
1

A pure bash version :

#!/usr/bin/env bash

IFS+=$'\r' # Handle possible carriage returns
while read -r line; do
    printf "%s\n" "$line"
    test "$line" = "[server]" && cat << EOF
PROTOCOL         = https
CERT_FILE        = cert.pem
KEY_FILE         = key.pem
EOF
done < app.ini
Philippe
  • 20,025
  • 2
  • 23
  • 32