Using "sed" to append to end of a file

I am currently using sed to write to an apache configuration file from stdin. I am using sed in this script to get around the bash script limition where the calling user does not have privileges to write to the file, so I can’t simply echo "..." >> outputfile.conf

Here is what I have for writing to the file:

echo "<VirtualHost *:80>
</VirtualHost>" | sudo sed -n "w/etc/apache2/sites-available/000-default.conf"

How can I later append to this same file?

if $enable_ssl; then
    echo "<VirtualHost *:443>
    </VirtualHost>" | sudo sed <opions-to-sed-here>
Asked By: user373785


Whithout echo:

string=$'"<VirtualHost *:443> 

sudo sed -i '$a'"${string}"'' file

The -i option tells sed to process a files in-place (optionally adding a suffix to the original version).

The sed script:

  1. $ match last line
  2. a append text after matching line

It won’t work on an empty file though (since there won’t be any lines of input to match the last line).

The usual replacement for shell > with higher/different privileges is:

echo "replace file content with this line" | sudo tee protectedFile >/dev/null

And if you want to append, use -a:

echo "append this line to file" | sudo tee -a protectedFile >/dev/null
Answered By: user232326

For completeness, if you have ed at hand:

echo "$
<VirtualHost *:80>
w" | sudo ed protectedFile
  1. $ go to last line
  2. a append, followed by data you want to append terminated by a line containing a single dot
  3. w stands for write (file)

The first two commands can be concatenated (yielding $a), yet this won’t work on empty file – separately it will, since it means “go to last line” (which is a no-op), followed by “append” rather than “append to last line”, which doesn’t really exist.

Answered By: peterph
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.