Alejandro Suarez
Alejandro Suarez

Reputation: 168

Create variables dynamically based on the number of tokens on a FOR /F loop

I have a file from which name i want to get information.

LOCAL DEPT, FIRST-FLOOR-DEPT.bat

I was already helped to separate using FOR /F loops the value i needed using the comma as the delimiter, but from that second part each of the word delimited by dash(-) i want assign them to a variable and from all those dynamically created variables make 1 that will unify them all. It sounds a bit weird i just can explain better. See the code i have so far testing and researching...

Setlocal EnableDelayedExpansion
SET c=0
SET getname=%~n0
for /f "tokens=2 delims=," %%F IN ("%getname%") DO (
    for /f "tokens=1* delims=- " %%G IN ("%%F") DO (
        SET /a c+=1
        SET step!c!=%%G
    )
)
for /L %%G in (!c!, -1, 1) do SET th=!step%%G!\
@echo %th%

Im expecting %th% to echo something like FIRST\FLOOR\DEPT but instead im getting only the first token like FIRST\

IMPORTANT: I have several files like this in which the amount of names sometimes is NAME, A-A other times is NAME, A-A-A or more so it cant be static :( in any way

Thanks in advance

Upvotes: 0

Views: 252

Answers (3)

vatsal mandaliya
vatsal mandaliya

Reputation: 1

You should use %random% for dynamic numbers. Such as:

set /a guns=%random%
echo you've %guns% guns! congratulations!

Upvotes: 0

vatsal mandaliya
vatsal mandaliya

Reputation: 1

for /l %%I in (1,1,10) do set randnum=%%i

Upvotes: -1

woxxom
woxxom

Reputation: 73596

Use string substitution:

Setlocal EnableDelayedExpansion
SET getname=%~n0
for /f "tokens=2 delims=," %%F IN ("%getname%") DO (
    set th=%%F
    rem Replace - with \
    set th=!th:-=\!
    rem trim the first space
    set th=!th:~1!
)
echo %th%

Upvotes: 2

Related Questions