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

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

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

#1 Post by SIMMS7400 » 20 Aug 2017 18:20

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!

DosItHelp
Expert
Posts: 239
Joined: 18 Feb 2006 19:54

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

#2 Post by DosItHelp » 21 Aug 2017 00:04

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"

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

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

#3 Post by aGerman » 21 Aug 2017 13:13

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

SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

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

#4 Post by SIMMS7400 » 21 Aug 2017 18:03

Thank you both so much!!! This is a major help!

Have a great night!

Post Reply