How to chain sed append commands

sed

I wanted to apply changes to config file with SED command, it requires inserting some lines in a few places after starting tags.

However, when I've tried:

sed '/\[httpd/\]/a secure_rewrites = false; /\[couchdb/\]/adelayed_commits = false' local.ini

I've found out, that after [httpd] a line was appended:

secure_rewrites = false; [couchdb]/a delayed_commits=false

which is obviously not what I've intended.

Is it possible to chain append commands?

Best Answer

Using GNU sed (BSD sed will not add newlines after the added text, unless you include a literal newline in the string that is added):

sed -e '/\[httpd\]/a\'   -e 'secure_rewrites = false;' \
    -e '/\[couchdb\]/a\' -e 'delayed_commits = false;' local.ini

If the file contains

[httpd]
[couchdb]

initially, then the above sed command will produce

[httpd]
secure_rewrites = false;
[couchdb]
delayed_commits = false;

Also note that the a command for appending text is supposed to be written a\ followed by the text appended. GNU sed is forgiving about omitting the \.


As a sed script (works in any sed):

/\[httpd\]/a\
secure_rewrites = false;
/\[couchdb\]/a\
delayed_commits = false;

This could be use on the command line as a literal single quoted sed script string (a newline has to come after the last line), or stored separately and fed into sed using

$ sed -f script.sed local.ini

With #!/usr/bin/sed -f, as the first line (assuming the path to sed is correct), the script could even be run directly:

$ ./script.sed local.ini
Related Question