sed, convert single backslash to double backslash

Given your sample input:

$ cat /tmp/foo
this newline must not be changed ---- \\n
this newline must be changed - \n

This seems to do what you want:

$ sed -e 's@\([^\]\)\\n@\1\\\\n@' /tmp/foo
this newline must not be changed ---- \\n
this newline must be changed - \\n

With \n in the LHS, you attempted to match a newline character instead of literal \n.

Try:

sed -e 's/\([^\]\)\(\\n\)/\1\\\2/g' file

or shorter with extended regular expression:

sed -E 's/([^\])(\\n)/\1\\\2/g' file

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.