windows 从批处理文件中的字符串中删除引号“”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21765687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove quotes "" from string in batch file
提问by Phiber
I use:
我用:
FOR /F "delims=" %%G IN ("%command%") DO SET command=%%~G
to remove "" quotes from variable %command%. If command = "Shutdown /s /t 00", after this line it will be: Shutdown /s /t 00. and it works.
But when command contains a string where are a equal sign (=), it remove also this caracter. Example:
before, command = "D:\temp\stinger --ADL --GO --Silent --ReportPath= D:\temp --ReportOnly --Delete --Program"
After, command= D:\temp\stinger --ADL --GO --Silent --ReportPath D:\temp --ReportOnly --Delete --Program
从变量 %command% 中删除 "" 引号。如果 command = "Shutdown /s /t 00",在这行之后它将是:Shutdown /s /t 00。它有效。但是当命令包含一个等号 (=) 的字符串时,它也会删除这个字符。示例:
之前,command = "D:\temp\stinger --ADL --GO --Silent --ReportPath= D:\temp --ReportOnly --Delete --Program"
之后,command= D:\temp\stinger --ADL --GO --Silent --ReportPath D:\temp --ReportOnly --Delete --Program
Look, the quotes "" are removed, but also the sign = .
看,引号 "" 被删除了,但符号 = 也被删除了。
So, how to remove the quotes "" without removing the equal character.
那么,如何在不删除等号的情况下删除引号 ""。
Thanks
谢谢
回答by unclemeat
Instead of your for loop through the command, you could just use string manipulation.
您可以只使用字符串操作,而不是通过命令进行 for 循环。
set command=%command:"=%
the values after command
are "=<nul>
so you're getting rid of quotation marks in the variable command. Just as an extra example, you could also do %command: =_%
to replace all spaces in command with underscores.
后面的值command
是"=<nul>
这样你摆脱了变量命令中的引号。作为一个额外的例子,你也可以%command: =_%
用下划线替换命令中的所有空格。
回答by dbenham
The reason your command fails is because the quotes in the string and the quotes in the IN() clause cancel each other out, so the remainder of the content is not quoted. The FOR /F parser treats an unquoted =
as a token delimiter that is converted into a space. You would also have problems with poison characters like &
, |
, etc.
你的命令失败的原因是因为字符串中的引号和 IN() 子句中的引号相互抵消,所以内容的其余部分没有被引用。FOR /F 解析器将未加引号的字符=
视为转换为空格的标记分隔符。您也将有毒药的字符,如问题&
,|
等等。
The problem is avoided by using delayed expansion. The delay state is toggled on before the FOR loop, and off within the loop so that any !
within the command are preserved.
使用延迟扩展可以避免该问题。延迟状态在 FOR 循环之前打开,在循环内关闭,以便!
保留命令中的任何内容。
setlocal enableDelayedExpansion
for /f "delims=" %%A in ("!command!") do endlocal & set "command=%%~A"
The major advantage of this approach is that you get the correct result regardless whether the command starts out quoted or not.
这种方法的主要优点是无论命令是否以引号开头,您都可以获得正确的结果。