Sed, convert single backslash to double backslash

regular expressionsedtext processing

I have a json string, which has a potpourri of doubly escaped/singly escaped newline chars. Json parser doesn't allow its string value to have single backslash escapes.

I need to uniformly make all of them to double escapes

Content looks like,

this newline must not be changed ---- \\n
this newline must be changed - \n

When i run sed command,

 sed -i 's/([^\])\n/\\n/g' ~/Desktop/sedTest 

it is not replacing anything

([^\]), this pattern is used to not change \n that already has one more backslash.

Best Answer

try

sed -i 's,\([^\\]\)\\n,\1\\\\n,'  file
sed -i 's,\([^\]\)\\n,\1\\\\n,'  file

where

  • \ must be escaped by \\\\
  • \( .. \) is the capture pattern
  • \1 on right hand is the first captured pattern.
  • second form with a single \ in [^\] as per @cuonglm suggestion.

You need to keep the pattern, or it will be discarded.

Related Question