brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: sed '/pattern/a text' adds a new line after every matching line

Sed
~/tips/tip-sed-append-line-after-match

printf 'key=1\nport=80\n' | sed '/^port=/a timeout=5'

Inserts a line of text after each line that matches a pattern.

Adding a setting right below another one is a small job that I used to do in an editor. sed can do it from a script, with the a command.

printf 'key=1\nport=80\n' | sed '/^port=/a timeout=5'
key=1
port=80
timeout=5

The address picks the lines, a appends the text after each of them. Two relatives work the same way: i inserts before the line, and c replaces the line with your text.

printf 'a\nb\n' | sed '/b/i before'
a
before
b

Use a line number to add something at the very end: sed -i '$a newline_at_end=1' file. I like that this also works when the last line has no trailing newline, because sed adds the missing one first.

The caveat is that the text goes in on every match, so a pattern that appears twice gives you two new lines. If the script may run more than once, check first with grep -q, or the file grows by a line each time.

Spaces matter a little: GNU sed strips the whitespace between a and the text, so to keep leading spaces in the new line, put a backslash in front of them.

Further reading: GNU sed manual

More Sed tips sed -n '$=' access.log echo 'hello world' | sed 's/.*/\U&/' sed 's/\/mnt\/user\/appdata\/old/\/mnt\/user\/appdata\/new/' app.conf sed -n '210,218p' /etc/nginx/nginx.conf sed -i.bak 's/old-host/new-host/g' config.txt All Sed tips (6) All topics

Link