将标记值设置为变量

时间:2014-11-21 15:22:21

标签: windows batch-file for-loop

我只是想知道如何将for语句中的标记值设置为批处理脚本中的变量,然后执行脚本所需的任何操作。

Myconfigfile.config有以下行:

 C:\logs|logfolder1|*.log|30
 C:\logs|logfolder12|*.log|30

所以我有这句话:

for /F "delims=| tokens=*" %%A in (Myconfigfile.config) do echo %%A

我是什么

 location="tokens=1"
 subfolder="tokens=2"
 pattern="tokens=3"
 range="tokens=4"

然后

 echo the location is  %location%
 echo the subfolder is  %subfolder%
 echo the pattern is  %pattern%
 echo the range is  %range%

显然我可以用4个语句做到这一点,但我怀疑有更好的方法可以做到这一点。

2 个答案:

答案 0 :(得分:1)

setlocal enableDelayedExpansion
    for /F "delims=| tokens=1-4" %%A in (Myconfigfile.config) do (
     set "location=%%A"
     set "subfolder=%%B"
     set "pattern=%%C"
     set "range=%%D"

      echo the location is  !location!
      echo the subfolder is  !subfolder!
      echo the pattern is  !pattern!
      echo the range is  !range! 
    )
endlocal

答案 1 :(得分:0)

这是未经测试的:

@echo off
setlocal EnableDelayedExpansion

rem Define the *names* of each one of the desired tokens:
rem (this is the only line that require changes)
set namesOfTokens=location subfolder pattern range


rem Assemble the correct "tokens=..." and set commands
set "tokens= ABCDEFGHIJKLMNOPQRSTUVWXYZ"
set "setCommands="
set i=0
for %%a in (%namesOfTokens%) do (
   set /A i+=1
   for %%i in (!i!) do set setCommands=!setCommands! set "%%a=%%%%!tokens:~%%i,1!" ^&
)

rem DO IT!
for /F "delims=| tokens=1-%i%" %%A in (Myconfigfile.config) do %setCommands:~0,-1%

echo the location is  %location%
echo the subfolder is  %subfolder%
echo the pattern is  %pattern%
echo the range is  %range%

非常重要,命令中的最后一个字符是“&”字符。请报告结果......