tl;dr:
ed myFile <<< $'a\nMy line here\n.\nwq'
A sad truth about programming is that you can never automate anything that you don't know how to do manually. If you don't know how to append a line manually with ed
, you can't hope to append a line automatically through ed
and a here-string.
The first step is therefore to look up how to append lines in ed
. Here's info ed
:
The sample sessions below illustrate some basic concepts of line
editing with 'ed'. We begin by creating a file, 'sonnet', with some
help from Shakespeare. As with the shell, all input to 'ed' must be
followed by a character. Comments begin with a '#'.
$ ed
# The 'a' command is for appending text to the editor buffer.
a
No more be grieved at that which thou hast done.
Roses have thorns, and filvers foutians mud.
Clouds and eclipses stain both moon and sun,
And loathsome canker lives in sweetest bud.
.
# Entering a single period on a line returns 'ed' to command mode.
# Now write the buffer to the file 'sonnet' and quit:
w sonnet
183
# 'ed' reports the number of characters written.
q
Ok, now let's adapt that to append a single line to a file and then quit:
$ touch myFile
$ ed myFile
a
Some text here
.
wq
And let's verify that it worked:
$ cat myFile
Some text here
Yay. Now that we're able to manually append a line, we just have to recreate the same input with a here-string. We can use cat
to verify that our input is correct:
$ cat <<< $'a\nMy line here\n.\nwq'
a
My line here
.
wq
Yup, this is exactly the input we used. Now we can plug that into ed
:
$ echo "Existing contents" > myFile
$ ed myFile <<< $'a\nMy line here\n.\nwq'
18
31
$ cat myFile
Existing contents
My line here