Where does the last newline character come from in this sed's result?
p
adds the newline character:
% printf 1 | sed 'p;s/1/2/'
1
2%
As can be seen, the 2
is printed without a trailing newline, but the 1 before it, from p
, is.
I think I found the answer. From the POSIX sed's documentation at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html, it states:
Whenever the pattern space is written to standard output or a named file, sed shall immediately follow it with a newline.
That means the p
command will always print pattern space as well as a newline. That also explains why there are newlines after 2\n\n1
, 4\n\n1\n3
and 6\n\n1\n3\n5
.
Please correct me if you think there is anything wrong with this. Thank you.