As others have said, e.g. in How to add a newline to the end of a file?, with GNU sed
(and some other implementations), $a\
adds a newline to the end of a file if it doesn’t have one.
Why it does this isn’t so clear, and the documentation doesn’t explain it. However, examining the source code does...
Let’s start with the documentation. $a\
is a variant of a
, exploiting a special case of a GNU extension:
As a GNU extension, the a
command and text can be separated into two -e
parameters, enabling easier scripting:
$ seq 3 | sed -e '2a\' -e hello
1
2
hello
3
$ sed -e '2a' -e "$VAR"
The way a
is implemented in sed
is with a queue of text to append, tracked in an append_queue
. When the time comes to process this queue, in a function called dump_append_queue
, the first step is
output_missing_newline (&output_file);
which adds a missing newline if necessary — to ensure that the appended text will be added to separate lines, not to the end of the current line. Then the contents of the queue are appended.
With sed -i '$a\'
, the missing newline is added if necessary, and then the queue is processed — but the queue is empty, so no additional change is made.
awk '1' file
- accept an input file with a terminating newline (valid POSIX text file) or without a terminating newline (invalid POSIX text file) and produce an output file that does have a terminating newline (i.e. is a POSIX text file) whether it was present in the input or not. – Ed Morton Dec 14 '21 at 16:23