Kousha
Kousha

Reputation: 36189

Replace newline (\n) with double backslash n (\\n)

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

Answers (2)

Blusky
Blusky

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

choroba
choroba

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

Related Questions