Windows 将标记值设置为变量
我只是想知道如何将for语句中的令牌值设置为批处理脚本中的变量,然后执行脚本所需的任何操作 Myconfigfile.config包含以下行:Windows 将标记值设置为变量,windows,batch-file,for-loop,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="tok
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"
然后
显然,我可以用4个for语句来实现这一点,但我怀疑有一种更有效的方法来实现这一点。这是未经测试的:
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
@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%
非常重要的是,long for命令中的最后一个字符是“&”字符。请报告结果…对不起。我的答案与卡玛卡的完全不同。我的方法允许插入/重新排序/删除任意数量的令牌,只修改一行。您只需输入:for/?
(我错误地认为您已经知道……)即可获得其他信息
@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%