Jayson Hurst
Jayson Hurst

Reputation: 1

sed search and replace \" but not \\"

I am trying to replace all escaped characters \" in a string with "" but not if \" is preceded by a \

So that input such as:

So far I have

$ echo sed -e 's/\([^\]\)\\"/\1""/;s/^\\"/""/'

but in the case of

$ echo '\"\"\"\"\"' | sed -e 's/\([^\]\)\\"/\1""/;s/^\\"/""/'` 

I am getting incorrect results.

Any help would be appreciated.

Upvotes: 0

Views: 115

Answers (3)

Jayson Hurst
Jayson Hurst

Reputation: 1

Using a sed loop will allow not having to pick a unique replacement string for an unknown dataset.

sed -e 's/^\\"/""/;:inner; s/\([^\]\)[\]"/\1""/g; t inner'


$ echo '\"\"\"\"' | sed -e 's/^\\"/""/;:inner; s/\([^\]\)[\]"/\1""/g;t inner'
""""""""
$ echo '\"\\"\"\"' | sed -e 's/^\\"/""/;:inner; s/\([^\]\)[\]"/\1""/g; t inner'
""\\"""""
$ echo '\"' | sed -e 's/^\\"/""/;:inner; s/\([^\]\)[\]"/\1""/g; t inner'
""
$ echo '\"\"' | sed -e 's/^\\"/""/;:inner; s/\([^\]\)[\]"/\1""/g; t inner'
""""
$ echo '\\"\"' | sed -e 's/^\\"/""/;:inner; s/\([^\]\)[\]"/\1""/g; t inner'
\\"""
$ echo '\"\\"' | sed -e 's/^\\"/""/;:inner; s/\([^\]\)[\]"/\1""/g; t inner'
""\\"
$ echo '\\\\\\\"' | sed -e 's/^\\"/""/;:inner; s/\([^\]\)[\]"/\1""/g; t inner'
\\\\\\\"

Upvotes: 0

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed 's/\\\\"/\n/g;s/\\"/""/g;s/\n/\\\\"/g' file

Replace all occurances of the string you want untouched by something else (\n is a good choice), replace the string you want changed globally, reinstate the first set of strings.

Upvotes: 1

Pedro M Duarte
Pedro M Duarte

Reputation: 28083

How about this:

#!/bin/bash

function myreplace {
    echo "$1" | sed -e "s/[\\]\"/MYDUMMY/g" \
                    -e 's/\\MYDUMMY/\\\\"/g' \
                    -e 's/MYDUMMY/""/g'
}

myreplace '\"\"\"\"'
myreplace '\"\\"\"\"'
myreplace '\"'
myreplace '\"\"' 
myreplace '\\"\"' 
myreplace '\"\\"' 
myreplace '\\\\\\\"'

Executing the script above results in:

""""""""
""\\"""""
""
""""
\\"""
""\\"
\\\\\\\"

Upvotes: 0

Related Questions