将令牌设置为变量

问题描述:

我只是想知道如何将令牌值从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来做到这一点,但我怀疑有更好的做法。

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 
+0

工作就像一个魅力!非常感谢你 – Tee 2014-11-21 16:54:39

这是未经测试:

@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% 

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

+0

也谢谢,npocmaka已经钉了它:) – Tee 2014-11-21 16:55:53

+0

对不起。我的回答与npocmaka的完全不同。我的方法允许插入/重新排序/删除任意数量的令牌,只修改一行。你可以通过输入'for /?'来获得其他信息(我错误地认为你已经知道了......) – Aacini 2014-11-22 00:38:11