命令提示符中的样例输入:
test.bat /p 1,3,4
预期结果:
1
3
4
我的代码如下:
@echo off
set arg = %1
set var = %2
if (%1)==(/p) (
... need code that will read and print each character of var
)
命令提示符中的样例输入:
test.bat /p 1,3,4
预期结果:
1
3
4
我的代码如下:
@echo off
set arg = %1
set var = %2
if (%1)==(/p) (
... need code that will read and print each character of var
)
您好!有关于您的问题可能存在潜在问题。如果 test.bat 是:
@echo %1%
那么
test 1,2,3
输出:
1
因为在这个上下文中,逗号被视为参数分隔符。
所以你需要用引号括起来:
test "1,2,3"
test 1:2:3
除非你希望将部件放置在%2、%3等位置,否则可以通过简单使用SHIFT
解决问题。
对于我的解决方案,我选择要求在组参数 "1,2,3" 周围加上引号(尽管通过更改 delims=,
指定要使用的字符可以轻松适应不同的分隔符)。
@echo off
setlocal ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS
set args=%~2
if "%1"=="/p" (
:NextToken
for /F "usebackq tokens=1* delims=," %%f in ('!args!') do (
echo %%f
set args=%%g
)
if defined args goto NextToken
)
调用方式:
readch.bat /p "1,2,3"
%~2
用于删除引号。
FOR
语句解析 args,将第一个标记放入 %f
,并将行的其余部分放入 %g
。
`goto NextToken' 行循环,直到没有更多标记为止。
@echo off
if "%1"=="/p" (
:LOOP
echo %2
shift
set arg=%2
if defined arg goto :LOOP else exit >nul
)
set params=%%~2
if (%1)==(/p) (
set params=%params:,= %
)
if "%params%" NEQ "" (
call :printer %params%
)
goto :eof
:printer
:shifting
if "%%1" NEQ "" (
echo %%1
) else (
goto :eof
)
shift
goto :shifting
goto :eof