Page 1 of 1

FOR LOOP Variable setting as %C - how to solve?

Posted: 20 Aug 2017 18:20
by SIMMS7400
Hi Folks -

I'm building a process that uses the script name to build log,error, export etc directories. Therefore, I parse the name accordingly:

Code: Select all

FOR /F "tokens=2* delims=_" %%A IN ("%~n0") DO (
   IF ["%%A"] NEQ [""] SET "A=%%A"
   IF ["%%B"] NEQ [""] SET "B=_%%B"
)


This works fine if the name is as such:

Code: Select all

STRING_STRING_STRING


However, the client would like the option to name the file with 3 delimiters, as such:

Code: Select all

STRING_STRING_STRING_STRING


The issue is when the code is as such:

Code: Select all

FOR /F "tokens=2* delims=_" %%A IN ("%~n0") DO (
   IF ["%%A"] NEQ [""] SET "A=%%A"
   IF ["%%B"] NEQ [""] SET "B=_%%B"
   IF ["%%C"] NEQ [""] SET "C=_%%B"
   


it will set %C% as _%C if the file name only contains (3) strings. Can you help me put a check in there saying if there is only 3 delimiters, then set %C% to null.

Thanks!

Re: FOR LOOP Variable setting as %C - how to solve?

Posted: 21 Aug 2017 00:04
by DosItHelp
Hey SIMMS7400,

It is possible you want tokens=1,2* ?
Also last line did you mean SET "C=_%%C" ?

Code: Select all

FOR /F "tokens=1,2* delims=_" %%A IN ("%~n0") DO (
   IF ["%%A"] NEQ [""] SET "A=%%A"
   IF ["%%B"] NEQ [""] SET "B=_%%B"
   IF ["%%C"] NEQ [""] SET "C=_%%C"

Re: FOR LOOP Variable setting as %C - how to solve?

Posted: 21 Aug 2017 13:13
by aGerman
You could also use the same syntax that I introduced to you in your former thread. That way it is also possible to assign an associative array for any number of tokens.

Code: Select all

@echo off &setlocal
set "name=STRINGa_STRINGb_STRINGc_STRINGd" &rem You would use set "name=%~n0" instead.

setlocal EnableDelayedExpansion
set "n=1"
set "token!n!=%name:_=" & set /a n+=1 & set "token!n!=%"

echo - Number of tokens: !n!
echo - Tokens:
for /l %%i in (1 1 !n!) do echo !token%%i!

pause

Steffen

Re: FOR LOOP Variable setting as %C - how to solve?

Posted: 21 Aug 2017 18:03
by SIMMS7400
Thank you both so much!!! This is a major help!

Have a great night!