How to escape the ampersand character while using sed

前端 未结 3 1463
囚心锁ツ
囚心锁ツ 2020-12-30 07:25

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 repla

3条回答
  •  有刺的猬
    2020-12-30 07:57

    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
    

提交回复
热议问题