Insert Text Above / Below a Match with sed

You can use sed to replace or delete strings but it can also insert text at specific points, here's how.
Here’s a couple of examples.
Inserting a line before a match:
Take note of the /i (insert) within the sed command:
$ echo "hello world" | sed "/^hello/i inserted before"
inserted before
hello world
Appending a line after a match:
Take note of the /a (append) within the sed command:
$ echo "hello world" | sed "/^hello/a appended after"
hello world
appended after
Prepending or appending extra new lines with \n:
This is using the GNU version of sed, it does operate differently if you’re
using the OpenBSD (macOS) version of sed due to how it supports \n.
If you want to do it in a way that works with both, it can be done but let’s focus on the common case with the GNU version first.
$ echo "hello world" | sed "/^hello/i inserted before with extra line breaks\n\n"
inserted before with extra line breaks
hello world
$ echo "hello world" | sed "/^hello/a \\\n\nappended after with extra line breaks"
hello world
appended after with extra line breaks
For the 2nd example we double escape the first line break. Without that I found
that sed returns literally n with only 1 of the line breaks. Also, using \ \n\n worked. I’m not exactly sure why we have to do either one but it is a
working solution.
As for making either example work with both the GNU and OpenBSD versions of
sed you can replace \n with a literal new line, such as this:
# Using single quotes instead of double is important here, so is using \ to
# break the script into multiple lines.
echo "hello world" | sed '/^hello/i inserted before with extra line breaks\
\
'
# Demo Video
Timestamps
- 0:12 – Inserting text before a match
- 0:49 – Appending text after a match
- 1:12 – Beware of adding extra line breaks
- 3:25 – Handling extra new lines in a cross OS compatible way
When was the last time you did this with sed? Let me know below.