windows 批处理文件中的字符串比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14954271/
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
string comparison in batch file
提问by dushyantp
How do we compare strings which got space and special chars in batch file?
我们如何比较批处理文件中有空格和特殊字符的字符串?
I am trying:
我在尝试:
if %DevEnvDir% == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"(
echo VS2010
)
But it gives an error "Files was unexpected at this time."
但是它给出了一个错误“此时文件是意外的”。
I tried:
我试过:
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"(
echo VS2010
)
But it gives an error "The syntax of the command is incorrect."
但它给出了一个错误“命令的语法不正确。”
Any ideas?
有任何想法吗?
回答by AjV Jsy
Just put quotes around the Environment variable (as you have done) :if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.
只需在 Environment 变量周围加上引号(正如您所做的那样):if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
但这是您放置左括号而没有空格的方式会使它混淆。
Works for me...
对我有用...
C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp.12\" (echo yes)
yes
回答by skataben
While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.
虽然@ajv-jsy 的答案大部分时间都有效,但我遇到了与@MarioVilas 相同的问题。如果要比较的字符串之一包含双引号 ("),则变量扩展会引发错误。
Example:
例子:
@echo off
SetLocal
set Lhs="
set Rhs="
if "%Lhs%" == "%Rhs%" echo Equal
Error:
错误:
echo was unexpected at this time.
Solution:
解决方案:
Enable delayed expansion and use ! instead of %.
启用延迟扩展并使用!代替 %。
@echo off
SetLocal EnableDelayedExpansion
set Lhs="
set Rhs="
if !Lhs! == !Rhs! echo Equal
:: Surrounding with double quotes also works but appears (is?) unnecessary.
if "!Lhs!" == "!Rhs!" echo Equal
I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.
到目前为止,我还无法使用这种技术打破它。它适用于空字符串和我扔给它的所有符号。
Test:
测试:
@echo off
SetLocal EnableDelayedExpansion
:: Test empty string
set Lhs=
set Rhs=
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.
:: Test symbols
set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
echo Lhs: !Lhs! & echo Rhs: !Rhs!
if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
echo.
回答by Bernardo Ravazzoni
The solution is DO NOT USE SPACES!
解决方案是不要使用空格!
IF "%DevEnvDir%"=="C:\" (