转义 findstr 搜索字符串中的引号
使用 findstr.exe 时如何正确转义搜索字符串中的引号?
示例:
findstr /misc:"namespace=\"" *.cs > ns.txt
这输出到控制台,而不是我指定的文件。
我直接在命令行上执行此操作,而不是实际上在批处理文件中执行此操作,尽管该信息也可能有用。
How can I properly escape a quote in a search string when using findstr.exe?
Example:
findstr /misc:"namespace=\"" *.cs > ns.txt
This outputs to the console, instead of to the file I specified.
I am doing this directly on the command line, not actually in a batch file, though that information might be useful too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果我错了,请纠正我,但我想我已经弄清楚了:
即使您的搜索字符串中有空格,这似乎也会给出正确的输出。它允许文件重定向、管道和同一 findstr.exe 调用中的其他文字正常工作。
我的问题中的原始命令不起作用,因为 cmd.exe 和 findstr.exe 对
"
字符都有特殊处理。我最终在 cmd.exe 的处理中得到了一组不匹配的引号。我的答案中的新命令有效,因为
^"
允许引用从 cmd.exe 传递到 findstr.exe,而\"
告诉 findstr.exe 忽略该命令的引用 嗯,我的解决方案编辑:
它正确的原因是完全错误的。
是正确的,但 当我传递错误的命令行时,cmd.exe 将此输入传递给程序:
在正确转义字符后,cmd.exe 将此输入传递给程序(并将输出重定向到文件):
Please correct me if I'm wrong, but I think I've figured it out:
This seems to give the correct output, even if you have spaces in your search string. It allows file redirection, piping, and additional literals in the same findstr.exe invocation to work correctly.
The original command in my question doesn't work because both cmd.exe and findstr.exe have special processing for the
"
character. I ended up with an unmatched set of quotes in cmd.exe's processing.The new command in my answer works because
^"
allows the quote to pass from cmd.exe to findstr.exe, and\"
tells findstr.exe to ignore that quote for command processing purposes, and treat it as a character literal.Edit:
Well, my solution was right, but the reason it is correct was totally wrong. I wrote a small program to test it.
I found out that cmd.exe passes this input to the program when I pass the bad command line:
With the characters escaped correctly, cmd.exe passes this input to the program (and redirects output to a file):
找到 回复:FINDSTR搜索一对引号并重定向/管道输出
我不知道为什么会这样。
但不适用于管道输出。请参阅相关链接管道 findstr 的输出
Found Re: FINDSTR search for a couble quote and redirect/pipe the output
I have no idea why this works.
Doesn't work for piping the output though. See the related link piping findstr's output
根据我的测试,正确的转义字符是反斜杠:
According to my tests the correct escape character is backslash:
这还不够吗:
?
编辑
如果您正在寻找一种在带引号的参数内传递
"
字符的方法,那么它可能是(使用您的示例)(
"
字符在带引号的字符串内重复两次)。Wouldn't this be just enough:
?
EDIT
If you were searching for a way to pass the
"
character inside a quoted parameter, then it could be (using your example)(the
"
character is repeated twice inside a quoted string).对于 findstr 程序和您正在使用的 shell,它们都必须进行转义。
https://ss64.com/nt/findstr-escapes.html
所以,如果从 powershell 运行,你的例子是
They must be escaped for both the findstr program and the shell you are using.
https://ss64.com/nt/findstr-escapes.html
So, if run from powershell, your example would be