如何转义单引号?

Mic*_*ant 4 shell scripting sed quoting escape-characters

这工作正常:

sed -i 's#    @driver.find_element(:xpath, "//a\[contains(@href,##' temp_spec.rb
Run Code Online (Sandbox Code Playgroud)

反对一个来源

@driver.find_element(:xpath, "//a[contains(@href,'change_district')]").click
Run Code Online (Sandbox Code Playgroud)

我只剩下:

'change_district')]").click`
Run Code Online (Sandbox Code Playgroud)

但是当我尝试在最后添加单引号时,它失败了:

sed -i 's#    @driver.find_element(:xpath, "//a\[contains(@href,\'##' temp_spec.rb

syntax error near unexpected token `('
Run Code Online (Sandbox Code Playgroud)

我正在使用\'转义单引号。

请注意,我使用 a#作为分隔符而不是普通/分隔符,因为/文本中有's。

pet*_*rph 12

单引号内的字符串由 shell 逐字使用(因此不能包含其他单引号,因为这将被视为一对中的最后一个)。也就是说,您有多种选择:

  • 结束单引号字符串,添加转义(通过反斜杠或双引号)单引号,然后立即开始字符串的以下部分:

    $ echo 'foo'\''bar' 'foo'"'"'bar'
    foo'bar foo'bar
    
    Run Code Online (Sandbox Code Playgroud)
  • 为您的字符串使用双引号:

    $ echo "foo'bar"
    foo'bar
    
    Run Code Online (Sandbox Code Playgroud)

    这当然意味着你必须小心你的 shell 在双引号内展开的内容;

  • 如果您使用的是可以理解\xHH\0nnn转义的实用程序(GNU sed 可以),您可以使用其中之一(ASCII 单引号位于代码点 39 (0x27),因此例如\x27)。