sed Scripting


Append

Not only can we swap text and delete lines, we can also add new lines to files.

This is an unusual thing for a non-interactive editor to do.

cat sedit.txt
The quick brown fox slept until noon
Our Scaly Starfish Ran Partly
This Fidgety Heron Seamlessly Complied

Using our trusty sedit.txt file, let's append a new line after the 1st line:

sed '1a\
Consolidated Promptly This Dashing DoubleBass'$'\n' sedit.txt

The 1 above indicates the line (address) we want to act on.

NOTE: you have to hit 'return' or 'enter' after you type sed '1a\

The quick brown fox slept until noon
Consolidated Promptly This Dashing DoubleBass
Our Scaly Starfish Ran Partly
This Fidgety Heron Seamlessly Complied
The backslash character after the “a” or “i” command doesn’t function as the part of an escape sequence, such as \t as a tab or \n as a newline. Instead, it indicates the beginning of the text in the new line we’re inserting.

This one is very strange, even for me:
The command is entered on multiple lines.

And adding the newline character has to done that way

In Bash, $'\n' expands to a single quoted newline character

Insert

append inserts text or a line AFTER the line number indicated. To insert text or a line (prepend) BEFORE another line requires a similar syntax:

sed '1i\
> Consolidated Promptly This Dashing DoubleBass'$'\n' sedit.txt
Consolidated Promptly This Dashing DoubleBass
The quick brown fox slept until noon
Our Scaly Starfish Ran Partly
This Fidgety Heron Seamlessly Complied

The > character is the sed prompt, so is not typed by the user.

Here we've inserted a line BEFORE the 1st line, and we've added a newline character $'\n' since we added a LINE to the file, not just some text. Leave out those characters if you are just adding some text in the midst of an existing line.