Replace newlines with literal \n

Is this all you're trying to do?

$ cat file
a
b
c

$ awk '{printf "%s\\n", $0}' file
a\nb\nc\n$

or even:

$ awk -v ORS='\\n' '1' file
a\nb\nc\n$

Run dos2unix on the input file first to strip the \rs if you like, or use -v RS='\r?\n' with GNU awk or do sub(/\r$/,""); before the printf or any other of a dozen or so clear, simple ways to handle it.

sed is for simple substitutions on individual lines, that is all. For anything else you should be using awk.


This should work with both LF or CR-LF line endings:

sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g' file

You could do this using sed and tr:

sed 's/$/\\n/' file | tr -d '\n'

However this will add an extra \n at the end.

Tags:

Regex

Sed