Reputation: 36189
I need to send a string that has newline as a JSON parameter. \n
causes an error and needs to be encoded as \\n
.
How can I replace \n
to \\n
in pure bash script in linux?
Upvotes: 2
Views: 3852
Reputation: 3784
If you want to replace \n (new line) by \n try this :
sed ':a;N;$!ba;s/\n/\\n/g'
ex:
$ echo -e "a\nb\nc" | sed ':a;N;$!ba;s/\n/\\n/g'
a\nb\nc
Upvotes: -3
Reputation: 241808
Use parameter expansion:
line='\n'
line=${line/\\n/\\\\n}
Using quotes might be more readable:
r=${line/'\n'/'\\n'}
If you want to replace all occurrences, double the first slash:
r=${line//'\n'/'\\n'}
# ^^
Upvotes: 4