我写了一个脚本,它遍历输入字符串的每个字符,并根据我需要做的不同的事情。只要我的输入不包含任何空格或双引号字符,这种方法就可以正常工作。我知道我必须逃避特殊字符,但出于某种原因,似乎我对空格和双引号做错了。
如果我使用参数" ab cd"运行批处理,则正确处理a和b,然后脚本在空白处停止并显示错误消息:"(SET意外发生这次)"。这似乎是指:
ECHO char: %char%
if %char%==0 (SET file=0.wav)
之前没有抛出此错误。但是,如果将%char%设置为空格,则此行似乎存在问题。显示一切应如何协同工作的方案是:
控制台输入:myScript.bat" ab cd" - > mytext =" ab cd" - > (循环)char =" a" - > char =" b" - > char =" " - > "(此时SET意外)"。
查看以下代码的更完整版本(无循环)。
:: get input (allow quoted inputs like "ab cd")
SET mytext=%~1
:: get first character from input
SET char=%mytext:~0,1%
:: works fine
if %char%==1 (...do something...)
if %char%==2 (...do something...)
if %char%==a (...do something...)
if %char%==b (...do something...)
::..also special characters work fine (some need escape sequence)
if %char%==^( (...do something...)
if %char%==^) (...do something...)
if %char%==: (...do something...)
if %char%==- (...do something...)
if %char%==+ (...do something...)
if %char%==$ (...do something...)
if %char%==. (...do something...)
if %char%==^! (...do something...)
if %char%==^' (...do something...)
答案 0 :(得分:1)
@echo off
setlocal enableextensions disabledelayedexpansion
rem Value to test
set "myText=1 <> () & !"" "
:loop
rem Quote it to avoid problems with special characters.
rem Closing quote is not included in value
SET "char=%mytext:~0,1%"
rem Test if we have something to test
if not defined char goto :done
rem Test first problematic characters that need escape
if ^%char%==^" echo quote & goto :next
if ^%char%==^& echo ampersand & goto :next
if ^%char%==^> echo greater than & goto :next
if ^%char%==^< echo lower than & goto :next
if ^%char%==^^ echo caret & goto :next
if ^%char%==^( echo open bracket & goto :next
if ^%char%==^) echo close bracket & goto :next
%= ... =%
rem Test for spaces
if "%char%"==" " echo space & goto :next
rem Test the rest of the options
if %char%==1 echo one & goto :next
if %char%==! echo exclamation & goto :next
%= ... =%
rem Once done, go to next character
:next
set "myText=%myText:~1%"
if defined myText goto :loop
:done
exit /b
答案 1 :(得分:0)
你需要确保有明显的东西可以评估,即使没有任何东西或只有白色空间来评估,所以试试这个:
if [%char%]==[] (...do something...)
if [%char%]==[0] (...do something...)
if [%char%]==[1] (...do something...)
etc...