sed rare-delimiter (other than & | / ?…)

后端 未结 8 2157
傲寒
傲寒 2020-12-17 17:42

I\'ve to apply the Unix command sed on a string (can contain #, !, /, ?, &, @ and all other characters) which can contains all types of

8条回答
  •  渐次进展
    2020-12-17 18:09

    There's no universal separator, but it can be escaped by a backslash for sed to not treat it like separator (at least unless you choose a backslash character as separator).

    Depending on the actual application, it might be handy to just escape those characters in both pattern and replacement.

    If you're in a bash environment, you can use bash substitution to escape sed separator, like this:

    safe_replace () {
        sed "s/${1//\//\\\/}/${2//\//\\\/}/g"
    }
    

    It's pretty self-explanatory, except for the bizarre part. Explanation to that:

    ${1//\//\\\/}
    ${            - bash expansion starts
      1           - first positional argument - the pattern
       //         - bash pattern substitution pattern separator "replace-all" variant
         \/       - literal slash
           /      - bash pattern substitution replacement separator
            \\    - literal backslash
              \/  - literal slash
                } - bash expansion ends
    

    example use:

    $ input="ka/pus/ta"
    $ pattern="/pus/"
    $ replacement="/re/"
    $ safe_replace "$pattern" "$replacement" <<< "$input"
    ka/re/ta
    

提交回复
热议问题