How can I replace a newline with its escape sequence?
Use:
sed ':a;N;$!ba;s/\n/\\n/g'
Which uses the answer from How can I replace a newline (\n) using sed? substituting an escaped newline character as the replacement to match the question here.
If you're dealing with a pipelined command, then I like @vossad01's answer above. However, in a multi-line script, I prefer normal Bash parameter expansion, which is both more efficient (doesn't need to fork a new process for sed
or create any pipes) and perhaps a bit easier to read:
${varName//$'\n'/\\n}
Reader's guide:
-
${...}
- Interpret the internal stuff using parameter expansion -
varName
- Name of the variable containing the content -
//
- Replace all instances of... -
$'\n'
- The literal newline character (we're turning the escape into the literal here) -
/
- Replace with... -
\\n
- The newline escape sequence ("\n"
): note that we had to escape the backslash itself
Example:
$ foo="$(printf '%s\n' $(seq 1 3))"
$ echo "$foo"
1
2
3
$ echo "${foo//$'\n'/\\n}"
1\n2\n3