Is there a way to escape quotes in ripgrep for MS Windows (Powershell or CMD)?

橙三吉。 提交于 2020-12-03 09:50:33

问题


I want to find a string "Hello (Hello starts with double quote) in text files using ripgrep.

Normally, in Bash or ZSH, this would work by escaping with backslash or surrounding with single quote:

rg \"Hello
rg '"Hello'

However, in MS Windows (Powershell and CMD), I've tried these but none of these worked:

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

Is there any way to escape single or double quotes using ripgrep in MS Windows?


回答1:


Verbatim string "Hello must ultimately be passed as \"Hello to rg ("\"Hello" would work too). That is, the verbatim " char. must be \-escaped:

From cmd.exe:

rg \^"Hello

^, cmd.exe's escape character, ensures that the " is treated verbatim and is removed by cmd.exe before calling rg.
Note that ^ isn't strictly necessary here, but it prevents the " from being considered the start of a double-quoted argument, which could make a difference if there were additional arguments.

From PowerShell:

rg \`"Hello

`, PowerShell's escape character, ensures that the " is treated verbatim and is removed by PowerShell before calling rg.


Arguably, the explicit \-escaping shouldn't be necessary, because it is the duty of a shell to properly pass arguments to target executables after the user has satisfied the shell's own escaping requirements (escaping the verbatim " with ^ in cmd.exe, and with ` in PowerShell).

In the context of PowerShell, this problematic behavior is summarized in this answer.

Note that in PowerShell this extra escaping is only needed if you call external programs; it isn't needed PowerShell-internally - such as when you call Select-String, as shown in js2010's answer.




回答2:


If you're in powershell you might as well do:

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

file:1:"hello



来源:https://stackoverflow.com/questions/59569846/is-there-a-way-to-escape-quotes-in-ripgrep-for-ms-windows-powershell-or-cmd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!