开发者

Regex for escaping quotes in a string

I have a string in the file

"abc def ghi " klm "ghi ";

I want to escape all occurrences of " in开发者_JAVA技巧 the string , output of the result

"abc def ghi \" klm \"ghi";


Since sed do not look ahead, I think we need to do it twice. Here is the code:

echo '"abc def ghi " klm "ghi ";' | sed -r 's/(\")/\\"/g'    | sed -r 's/(^\"|\";$)/";/g'
# ^ Print the text                  ^ Replace all " with \"    ^ Replace the first and the last \" back to "

Hope this helps


awk

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

or

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜