sed, convert single backslash to double backslash
8,600
Solution 1
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.
Solution 2
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
Solution 3
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
Related videos on Youtube
Author by
don_crissti
Updated on September 18, 2022Comments
-
don_crissti over 1 year
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. -
Admin over 8 yearshi, why do we need
\1
in the destination pattern? -
Andy Dalton over 8 yearsAssume the input was:
foo\n
. The[^\]
part capture part will match the secondo
infoo
. The\1
is a group that contains that portion of the match. I include\1
so that you don't loose that character. -
Admin over 8 yearsin simpler sed replaces like,
sed 's,abc,def,
, i never have to capture a pattern to make sure, that the pattern gets replaced.. in this case alone, why is\1
used to capture it? -
Арсений Черенков over 8 yearsin s/abc/dev/ , abc is discarded.
-
Admin over 8 yearsmakes sense....