First, this is not a duplicate of, e.g., How can I replace each newline (\n) with a space using sed?
What I want is to exactly replace every newline (\n
) in a string, like so:
-
printf '%s' $'' | sed '...; s/\n/\\&/g'
should result in the empty string
-
printf '%s' $'a' | sed '...; s/\n/\\&/g'
should result in
a
(not followed by a newline) -
printf '%s' $'a\n' | sed '...; s/\n/\\&/g'
should result in
a\
(the trailing
\n
of the final line should be replaced, too)
A solution like :a;N;$!ba; s/\n/\\&/g
from the other question doesn't do that properly:
printf '%s' $'' | sed ':a;N;$!ba; s/\n/\\&/g' | hd
works;
printf '%s' $'a' | sed ':a;N;$!ba;s/\n/\\&/g' | hd
00000000 61 |a|
00000001
works;
printf '%s' $'a\nb' | sed ':a;N;$!ba;s/\n/\\&/g' | hd
00000000 61 5c 0a 62 |a\.b|
00000004
works;
but when there's a trailing \n
on the last line
printf '%s' $'a\nb\n' | sed ':a;N;$!ba;s/\n/\\&/g' | hd
00000000 61 5c 0a 62 0a |a\.b.|
00000005
it doesn't get quoted.