Search code examples
bashsed

How to append a line at the end of the file using sed


The following command works fine assuming the test.txt file already exists:

sed -i -e '$a\
This line was appended at the end.' test.txt

But this command take two lines. I would rather have a single line instead, like so:

sed -i -e '$a\ This line was appended at the end.' test.txt

But unfortunately it raises an error:

sed: 1: "$a\ This line was appended at the end.": extra characters after \ at the end of a command

Would it be possible to get this command working as a single line?


Solution

  • You can use $'\n' which the shell translates to a newline:

    sed -i -e '$a\'$'\n''This line was appended at the end.' test.txt
    

    or

    sed -i -e $'$a\\\nThis line was appended at the end.'
    

    The first $ introduces the $'' quotes that make it possible to enter a newline as \n. The second $ is a sed address meaining the last line. The command a menans append.