我编写了一个脚本,它会遍历输入字符串的每个字符,并根据我需要执行不同操作的字符。只要我的输入不包含任何空格或双引号字符,这种方法就可以很好地工作。我知道我必须转义特殊字符,但由于某种原因,我似乎对空格和双引号做错了。
如果我使用参数“ab cd”运行批处理,a 和 b 会被正确处理,然后脚本会在空白处停止并显示错误消息:“(此时 SET 是意外的)”。这似乎是指:
ECHO char: %char%
if %char%==0 (SET file=0.wav)
之前没有抛出过这个错误。但将 %char% 设置为空白时,这一行似乎有问题。显示一切如何协同工作的方案是:
控制台输入: myScript.bat "ab cd" -> mytext = "ab cd" -> (loop) 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...)
@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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)