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.

Leave a Comment