tags:

views:

72

answers:

4

I have a string in the file

"abc def ghi " klm "ghi ";

I want to escape all occurrences of " in the string , output of the result

"abc def ghi \" klm \"ghi";
A: 

awk

$ awk '{gsub("\"","\\\"")}1' file
abc def ghi \" klm \"ghi

or

$ awk -vq="\042" '{gsub(q,"\\"q)}1' file
abc def ghi \" klm \"ghi
ghostdog74
A: 

I managed to do it in sed

> echo "abc def ghi \" klm \" ghi"
abc def ghi " klm " ghi
> echo "abc def ghi \"klm \" ghi" | sed 's/"/\\"/g'
abc def ghi \" klm \" ghi
phasetwenty
In this case, however, the shell has taken care of the first and last quotes for you. This would not be the case if the input was taken from a file.
lacqui
+1  A: 
NawaMan
A: 

You don't have to pipe sed into sed, you can do it all in one step:

echo '"abc def ghi " klm "ghi ";' | sed 's/\"/\\"/g; s/^\\"\(.*\)\\"/\"\1\"/'

Some versions of sed prefer it this way:

echo '"abc def ghi " klm "ghi ";' | sed -e 's/\"/\\"/g' -e 's/^\\"\(.*\)\\"/\"\1\"/'

I used a capture group, but you could use alternation instead.

Dennis Williamson