I have the following problem: in a script, that must not be executed as root, I have to write a line to a newly created, empty file. This file is in /etc, so I need elevated privilages to write to it.
Creating the file is simple:
sudo touch /etc/myfile
sudo echo "something" > /etc/myfile
sudo sed -i -e "\$aInsert this" /etc/differntfile
You can use
echo "something" | sudo tee /etc/myfile # tee -a to append
Or redirect to
/dev/null if you don't want to see the output:
echo "something" | sudo tee /etc/myfile > /dev/null
Another option is to use
sh -c to perform the full command under sudo:
sudo sh -c 'echo "something" > /etc/myfile'
Regarding doing this with
sed: I don't think it is possible. Since
sed is a stream editor, if there is no stream, there is nothing it can do with it.