脚本 1:
输入 ("Remove Quotes.cmd" "This is a Test")
该脚本的作用是删除指定文本中的引号。其中,第一个参数为脚本名称,第二个参数为需要处理的文本内容。
@ECHO OFF
REM Set "string" variable to "first" command line parameter
SET STRING=%1
REM Remove Quotes [Only Remove Quotes if NOT Null]
IF DEFINED STRING SET STRING=%STRING:"=%
REM IF %1 [or String] is NULL GOTO MyLabel
IF NOT DEFINED STRING GOTO MyLabel
REM OR IF "." equals "." GOTO MyLabel
IF "%STRING%." == "." GOTO MyLabel
REM GOTO End of File
GOTO :EOF
:MyLabel
ECHO Welcome!
PAUSE
输出(没有,%1不是空白、空的或NULL):
使用上述脚本1在没有任何参数的情况下运行“Remove Quotes.cmd”
输出(%1为空白、空的或NULL):
Welcome!
Press any key to continue . . .
注意:如果你在一个
IF ( ) ELSE ( )
语句中设置一个变量,直到它退出"IF"语句(除非启用了“延迟变量扩展”;一旦启用,请使用感叹号“!”代替百分号“%”符号),该变量将不可用于DEFINED。
例如:
脚本2:
Input ("Remove Quotes.cmd" "This is a Test")
@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET STRING=%0
IF 1==1 (
SET STRING=%1
ECHO String in IF Statement='%STRING%'
ECHO String in IF Statement [delayed expansion]='!STRING!'
)
ECHO String out of IF Statement='%STRING%'
REM Remove Quotes [Only Remove Quotes if NOT Null]
IF DEFINED STRING SET STRING=%STRING:"=%
ECHO String without Quotes=%STRING%
REM IF %1 is NULL GOTO MyLabel
IF NOT DEFINED STRING GOTO MyLabel
REM GOTO End of File
GOTO :EOF
:MyLabel
ECHO Welcome!
ENDLOCAL
PAUSE
输出:
C:\Users\Test>"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd" "This is a Test"
String in IF Statement='"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"'
String in IF Statement [delayed expansion]='"This is a Test"'
String out of IF Statement='"This is a Test"'
String without Quotes=This is a Test
C:\Users\Test>
注意:它也会从字符串内部删除引号。
例如(使用脚本1或2):
C:\ Users \ Test \ Documents \ Batch Files>“Remove Quotes.cmd”“This is”a“Test”
输出(脚本2):
String in IF Statement='"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"'
String in IF Statement [delayed expansion]='"This is "a" Test"'
String out of IF Statement='"This is "a" Test"'
String without Quotes=This is a Test
在脚本2中执行("Remove Quotes.cmd"),不带任何参数:
输出:
Welcome!
Press any key to continue . . .
%1
中有偶数个双引号,if "%1" == "" GOTO MyLabel
就不会致命地终止脚本的执行。我发现,如果%1
中有奇数个双引号,则会出现以下错误并终止脚本的执行:The syntax of the command is incorrect.
下面的解决方案使用方括号来解决问题,被标记为正确答案,但似乎没有任何改善。当%1
中有奇数个双引号时,该解决方案也会出现相同的错误。 - Susam PalIF DEFINED
只能用于环境变量而不能用于脚本变量,这浪费了很多潜力! - kayleeFrye_onDeckCMD.bat arg1, , arg3
,以下内容是正确的:%2 == %arg3
。 - johny whyIF /i NOT "%var%"==""
是检查脚本变量是否已定义的几乎唯一安全方法。这比IF DEFINED %var%
难看得多 :( - kayleeFrye_onDeck