Why does sed require 3 backslashes for a regular backslash?

后端 未结 7 1650
余生分开走
余生分开走 2020-11-29 01:26

I\'m curious, why does sed need 3 \\ just to recognize one? I\'d understand it needing 2, but 3 I don\'t.

EDIT: here\'s an example on my Windows compute

7条回答
  •  情话喂你
    2020-11-29 01:54

    That's due to sh's double-quoted string parsing rule.

    Posix specifies how sh parses double-quoted strings.

    The backslash shall retain its special meaning as an escape character (see Escape Character (Backslash)) only when followed by one of the following characters when considered special: $ ` " \

    In other words, sh lefts the backslash which is followed by characters other than $ ' " .

    So, if sh meets the double-quoted string sed "s/\\\/\//", sh parses it as follows.

    1. The first two \\ is changed into \. Because the first \ is followed by the second \.
    2. The third and fourth \ is still left in the string. Because both of them are followed by /, which is not special in double-quoted string.

    After pasring, sh passes the string s/\\/\// to sed, which substitutes the first occurence of \ into /.

    With same reasoning, when sh meets the string, "sed s/\\\\/\//", sh passes /\\/\// to sed, which also substitutes the first occurence of \ into /.

提交回复
热议问题