Replace single and double quotes with backslash prefix
People,
I am trying to get a sed command to replace \'
with '
and \\"
with \"
in a file. I tried below using sed
but can't figure out how to separate single and double quotes.
$ cat temp
\'
\\"
$ cat temp | sed 's#\\\\"#\\"#' | sed 's#\\'#'#'
'
"
desired result:
' \"
Can someone point out what I am doing wrong.
Note. I want to apply this change to the entire file entry
source to share
Tested with GNU sed 4.2.2
, not sure about portability
I modified the input sample to better show how the command works:
$ cat temp
\' and \\' and \\\'
\" and \\" and \\\"
$ sed -E 's/\\([\x27"])/\1/g' temp
' and \' and \\'
" and \" and \\"
-
-E
use ERE, some versionssed
use-r
-
\\([\x27"])
will match\
followed by'
or"
, and only the quote character -
\1
the captured group is used as a replacement -
g
the modifier will replace all such occurrences in the string
To change only \\"
, not any occurrence\"
$ sed -E 's/\\\x27/\x27/g; s/\\\\"/\\"/g;' temp
' and \' and \\'
\" and \" and \\"
source to share
This might work for you (GNU sed):
sed 's/\\\(\\['\''"]\)/\1/g' file
or
sed -r 's/\\(\\['\'"])/\1/g' file
The problem is that the single quote is used to quote the sed expression and therefore must be quoted in the shell, hence \'
. Using a character class for a single quote or double quote allows the substitution to use a backreference and therefore simplify the right side of the substitution.
source to share
One of the difficulties you run into is that you are writing your expression as a command line argument to sed, and therefore need to be quoted for your shell. It's much easier if you write your sed program in a file:
#!/bin/sed -f s/\\'/'/g s/\\\\"/\\"/g
You need to double each \
one to quote them in the command s
, but there are no extra quotes that the shell would need.
Demonstration:
$ cat 44649501.input
\'
\\"
$ ./44649501.sed <44649501.input
'
\"
source to share