2014-11-21 60 views
0

我只是想知道如何將令牌值從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來做到這一點,但我懷疑有更好的做法。

回答

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

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

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% 

這是非常重要,從長遠的命令最後一個字符是 「&」 字。請報告結果...

+0

也謝謝,npocmaka已經釘了它:) – Tee 2014-11-21 16:55:53

+0

對不起。我的回答與npocmaka的完全不同。我的方法允許插入/重新排序/刪除任意數量的令牌,只修改一行。你可以通過輸入'for /?'來獲得其他信息(我錯誤地認爲你已經知道了......) – Aacini 2014-11-22 00:38:11