Tee
Tee

Reputation: 3

Setting for tokens values to variables

I was just wondering how you would set the token values from a for statement into variables in a batch script then perform whatever actions your script requires.

Myconfigfile.config has below lines:

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

So I have this line:

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

I what

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

Then

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

Obviously I could do that with 4 for statements but I suspect there is a better more effcient way of doing it.

Upvotes: 0

Views: 190

Answers (2)

Aacini
Aacini

Reputation: 67216

This is untested:

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

It is very important that last character in the long for command be the "&" character. Please, report the result...

Upvotes: 0

npocmaka
npocmaka

Reputation: 57252

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

Upvotes: 1

Related Questions