Using "sed" to append to end of a file
Solution 1
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
Solution 2
Whithout echo
:
string=$'"<VirtualHost *:443> \
... \
</VirtualHost>"'
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:
$
match last linea\
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).
Solution 3
For completeness, if you have ed
at hand:
echo "$
a
<VirtualHost *:80>
...
</VirtualHost>
.
w" | sudo ed protectedFile
$
go to last linea
append, followed by data you want to append terminated by a line containing a single dotw
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.
Related videos on Youtube
Admin
Updated on September 18, 2022Comments
-
Admin over 1 year
I am currently using
sed
to write to an apache configuration file fromstdin
. I am usingsed
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 simplyecho "..." >> 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> fi
-
Arkadiusz Drabczyk over 4 yearsCould you simply use
tee -a
? -
Hastur over 4 yearsDon't you have
/bin/echo
in the system? It is a POSIX specification. In that case you should simply may be able to use something likesudo /bin/echo "whatever" >> outputfile.conf
. -
Admin over 4 years@Hastur No you can't do that if you are writing to a file owned by root. If am "user" and I run
sudo echo "whatever" >> outputfile.conf
the writing/appending tooutput.conf
is done by the shell, not byecho
. This means I don't havesudo
permissions when the output is attempted to be written to the file. Isaac's answer usingsudo tee -a
is the correct answer. In that scenariotee
does havesudo
permissions and can write tooutputfile.conf
. -
Hastur over 4 years@Makerik thanks, I missed that point. BTW, in order to avoid the use of
tee
(or whatever other executable), it is needed to write something likesudo /bin/bash -c 'echo "whatever" >> outputfile.conf'
(or/bin/ash
,/bin/dash
, etc etc...).
-
-
Grump over 4 yearsI'm not sure why you have the double single quote at the end of the sed command?