Append text to file using sed
Use $ a
.
sed -i "$ a some text" somefile.txt
Adding a late post because while the accepted answer is the simplest solution to this problem, the question actually highlights a couple of common situations:
- Need to edit a file via sudo
- Trying to use
sed
to modify an empty file.
In short, you can't touch
, then edit a file with sed
.
Sed doesn't work on empty files, but occasionally you need to do the equivalent of
sudo echo "some text" >> somefile.txt
sudo doesn't like the redirect, but there are workarounds:
echo "some text" | sudo tee --append somefile.txt
or if pipes are not an option either, or you simply must use sed, or you just like complexity:
dd if=/dev/zero count=1 bs=1 of=somefile.txt
sed -i '$ a some text' somefile.txt
sed -i '1 d' somefile
On some systems,. you might have to use sed -i -e '$ a ...
If you're just appending text to the end of the file then you wouldn't use sed in the first place.
echo "some text" >> somefile.txt