Sad, but I don't find any method to prevent sed from adding new line to output when N
command is used. I didn't want to some workaround to like add new line before processing and removing it after, but seems like there is no other method.
This is the final solution with workaround:
sed ':a;$!{N;ba};s/\n/\\n/g;s/a/_/g' <<< "$VAR" | tr -d '\n'
<<<
like echo adds new line into input string, tr
removes it.
With that line all test are OK:
$ echo -e "abc" | sed ':a;$!{N;ba};s/\n/\\n/g;s/a/_/g' | tr -d '\n' | hexdump -C
00000000 5f 62 63 |_bc|
$ echo -e "abc\n" | sed ':a;$!{N;ba};s/\n/\\n/g;s/a/_/g' | tr -d '\n' | hexdump -C
00000000 5f 62 63 5c 6e |_bc\n|
$ echo -e "abc\n\n" | sed ':a;$!{N;ba};s/\n/\\n/g;s/a/_/g' | tr -d '\n' | hexdump -C
00000000 5f 62 63 5c 6e 5c 6e |_bc\n\n|
P.S.: thanks potong for figuring out the :a;$!{N;ba}
.
P.P.S.: If someone will give working answer without tr
, I will re-accept it.