tags:

views:

165

answers:

3

I'm trying to replace \" (backslash doouble quote) by ' (quote) using sed.

sed "s/\\\"/\'/g" file.txt

The command doesn't work as expected. It replaces all the " in the text file, not only the \".

It does the same thing as sed "s/\"/\'/g" file.txt

I'm working on Mac OS X Leopard.

Does any one have a clue?

+5  A: 

You're dealing with the infamous shell quoting problem. Try using single quotes around the s//g instead, or add an extra escape:

sed "s/\\\\\"/\'/g"
Paul Tomblin
The extra escape worked ! Thanks Paul.
jlfenaux
I don't think this is exactly the shell quoting problem, since the problem is in sed's interpretation of the string and not the shell's. Sed sees s/\"/\'/g and interprets the \" the same as ".
William Pursell
@William - I characterize it as "shell quoting problem" because bash "swallows" one of the escapes so that sed doesn't see it.
Paul Tomblin
+2  A: 

Quoting issues with bash are fun.

$ cat input
"This is an \"input file\" that has quoting issues."
$ sed -e 's/\\"/'"'"'/g' input
"This is an 'input file' that has quoting issues."

Note that there are three strings butted together to make the sed script:

  • s/\\"/
  • '
  • /g

The first and last are quoted with single quotes, and the middle is quoted with double quotes.

Matthew's command works by joining two strings instead of three:

  • s/\\"/
  • '/g

where the first is single-quoted and the second double-quoted.

Greg Bacon
Nice. You can simplify it slightly to sed -e 's/\\"/'"'/g" input
Matthew Flaschen
A: 

don't have to use too many quotes. \042 octal is for " and \047 is octal for single quote

awk '{gsub("\042","\047") }{print}' file
ghostdog74