Reputation: 1139
cat file.json
gives me what I want to capture inside of $JSON
:
{
key: "value\nwith\nnewline\nchars"
}
I can't do JSON=$(cat file.json)
though because then the newline characters are translated and I get after echo $JSON
or echo -e $JSON
.
{
key: "value
with
newline
chars"
}.
How can I preserve the newline characters inside of $JSON
?
Upvotes: 1
Views: 318
Reputation: 295520
Capture using command substitution doesn't perform the translation you're worried about here, but using echo
(or misusing printf
by substituting into the format string rather than a separate parameter) will.
To emit a variable with backslash sequences intact, use:
printf '%s\n' "$JSON"
This avoids behavior that echo
can have (either explicitly with bash's noncompliant extension for echo -e
, or implicitly when the xpg_echo
flag is enabled in bash, or as default out-of-the-box behavior with other, POSIX+XSI-compatible /bin/sh
implementations) wherein escape sequences are replaced by echo
, even if the variable passed as an argument had a multi-character backslash sequence.
Upvotes: 3