批处理文件:变量中的变量

时间:2013-10-28 20:56:01

标签: batch-file batch-processing

我有一个我正在尝试解析的复杂字符串。我有一个简短的子程序来细化两个特定字符的索引,我需要在它们之间的字符串。所以问题是: 如何在另一个变量的字符串操作中使用变量?

以下是一些示例代码:

@ECHO off

set start=2
set end=5
set str=Hello World

echo %str:~2,5%
echo %str:~%start%,%end%%

如何获取第二个回显以显示第一个回显显示的内容? (现在第二个回声只显示我想要的东西,它会按原样崩溃)

2 个答案:

答案 0 :(得分:3)

@ECHO off

set start=2
set end=5
set str=Hello World

setlocal enableDelayedExpansion
echo %str:~2,5%
echo !str:~%start%,%end%!
endlocal

或(最坏的方式)

@ECHO off

set start=2
set end=5
set str=Hello World

echo %str:~2,5%
call echo %%str:~%start%,%end%%%

或(如果开始和结束定义以及子字符串都在括号上下文中,则可以使用)

@ECHO off

set start=2
set end=5
set str=Hello World

echo %str:~2,5%
setlocal enableDelayedExpansion
for /f "tokens=1,2" %%a in ("%start% %end%") do echo !str:~%%a,%%b!
endlocal

或(也是一种糟糕的方式)

@ECHO off

set start=2
set end=5
set str=Hello World

call :substr "%str%" %start% %end%
goto :eof

:substr
setlocal enableDelayedExpansion
set "_str=%~1"
echo !_str:~%2,%3!
rem without delayedExpansion
rem call echo %%_str:~%2,%3%%
endlocal
goto :eof

答案 1 :(得分:0)

CALL echo %%str:~%start%,%end%%%

代替您的版本。无需enabledelayedexpansion