How to escape the ampersand character while using sed

♀尐吖头ヾ 提交于 2020-12-24 08:47:06

问题


I want to replace all single quotes in a string with two single quotes using sed. But when the string contains the & character, the sed command is not replacing single quotes that come after that. How can I escape the & character so that the single quotes after it are still replaced?


回答1:


You don't need to escape anything in the input:

$ echo "123 ' foo & b'ar" | sed "s/'/''/g"
123 '' foo & b''ar

However, in the 'replacement' part of the s command & has a special meaning: it means 'match'. That's why the above command can be re-written as:

$ echo "123 ' foo & b'ar" | sed "s/'/&&/g"
123 '' foo & b''ar

Escape it with a \ like everything else that needs to be escaped, if needed:

$ echo "123 ' foo & b'ar" | sed "s/'/'\&'/g"
123 '&' foo & b'&'ar



回答2:


It's easier to answer if you post your code, but I'm guessing you're not escaping the ampersand. Change & to \& if you want a literal ampersand.

See section 3.1.2 of The sed FAQ for a more detailed explantion, if you're curious.




回答3:


It's working for me

bash>echo "'This is a string with 'single quote' & '&'" | sed "s/'/''/g"
''This is a string with ''single quote'' & ''&''


来源:https://stackoverflow.com/questions/11307759/how-to-escape-the-ampersand-character-while-using-sed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!