Home > Software design >  Search and replace backslash except one thing
Search and replace backslash except one thing

Time:07-26

I want to replace \ with \\ except \N. So I got so far

sed ‘s/\\/\\\\/g’

But I’m not sure how to add ignore

Sample:

aa  \N  aa
\N  aa  aa
aa  aa  \N
\N  \N  aa
\N  aa  \N
aa  \N  \N
\N  \N  \N
aa  aa  aa
\N  bb  \N
\       aa

should be:

aa  \N  aa
\N  aa  aa
aa  aa  \N
\N  \N  aa
\N  aa  \N
aa  \N  \N
\N  \N  \N
aa  aa  aa
\N  bb  \N
\\      aa

CodePudding user response:

You could do:

echo '\ \\ \N \\N' |
sed -E 's/\\(N)|(\\)/\\\1\2/g'
\\ \\\\ \N \\\N

CodePudding user response:

You could try this 's/\/\([^N]\)/\/\/\1/'

Simple match / and the character after, requiring to not match N character.

The matched character (other from N) will be stroed in captureing group and can be used in replacement with \1 :)

Results from sed.js.org:

enter image description here

CodePudding user response:

What you need is a negative lookahead, which is a way to say: I want to match a pattern that is not followed by something.

As far as I know, sed does not support lookarounds, but you can keep most of your syntax with this perl command:

perl -pe 's/\\(?!N)/\\\\/g'
  • Related