【问题标题】:Is there a way to escape quotes in ripgrep for MS Windows (Powershell or CMD)?有没有办法在 ripgrep for MS Windows(Powershell 或 CMD)中转义引号?
【发布时间】:2020-01-02 20:51:09
【问题描述】:

我想使用ripgrep在文本文件中查找字符串"Hello(Hello 以双引号开头)。

通常,在 Bash 或 ZSH 中,这将通过使用反斜杠转义或用单引号括起来来工作:

rg \"Hello
rg '"Hello'

但是,在 MS Windows(Powershell 和 CMD)中,我已经尝试过这些,但这些都不起作用:

rg \"Hello
rg '"Hello'
rg `"Hello
rg '`"Hello'

有没有办法在 MS Windows 中使用 ripgrep 转义单引号或双引号?

【问题讨论】:

  • 是什么阻止您使用内置的 Windows 方法和/或工具而不是 ripgrep?
  • @Compo:使用 ripgrep 的一个令人信服的理由是它的速度;另一个是其友好的输出格式(突出显示匹配的行部分)。虽然 PowerShell 7.0 中的 Select-String 现在也有这样的突出显示,但速度要慢得多。在 PowerShell 中使用 Select-String 可以避免令人头疼的问题,但如果您调用 findstr.exe(其正则表达式支持较差),您将面临同样的问题。

标签: powershell cmd ripgrep


【解决方案1】:

逐字字符串"Hello 最终必须作为\"Hello 传递给rg"\"Hello" 也可以)。也就是说,逐字逐句的" 字符。必须是\-escaped

来自cmd.exe

rg \^"Hello

^cmd.exe 的转义字符,确保" 被逐字处理,并在调用rg 之前被cmd.exe 删除。
请注意,^ 在这里并不是绝对必要的,但它可以防止 " 被视为双引号参数的开头,如果有其他参数,这可能会有所不同。

来自 PowerShell

rg \`"Hello

`,PowerShell 的转义字符,确保 " 被逐字处理,并在调用 rg 之前被 PowerShell 删除。


可以说,显式的\-escaping 应该是不必要的,因为在用户满足 shell 自己的转义要求后,shell 有责任将参数正确传递给目标可执行文件(在cmd.exe 中使用^ 逐字转义",在PowerShell 中使用`)。

在 PowerShell 的上下文中,这种有问题的行为在 this answer 中进行了总结。

请注意,在 PowerShell 中,仅当您调用 外部程序 时才需要这种额外的转义; PowerShell-内部不需要它——比如当你调用Select-String时,如js2010's answer所示。

【讨论】:

  • 这些似乎也有效。 Powershell:rg '\"Hello',CMD:rg "\"Hello"
【解决方案2】:

如果您使用的是 powershell,您不妨这样做:

get-childitem file | select-string '"hello'

file:1:"hello

【讨论】:

    【解决方案3】:

    您可以使用rg -F \"Hello

       -F, --fixed-strings 
       Treat the pattern as a literal string instead of a regular expression. When this flag is used, special regular expression meta characters such as .(){}*+ do not
       need to be escaped.
    
       This flag can be disabled with --no-fixed-strings.
    

    【讨论】:

      猜你喜欢
      • 2012-04-13
      • 2021-12-27
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多