Wergio
Wergio

Reputation: 45

loop througt through a comma separated string in batch file

Why this code:

@echo OFF
SETLOCAL EnableDelayedExpansion
SET /A i=0

FOR /F "USEBACKQ tokens=* delims=," %%a IN (`echo aaa,bbb,ccc`) DO (
SET /A i+=1
echo !i! %%a
)

gives me this output?

1 aaa bbb ccc

when instead I want this:

1 aaa
2 bbb
3 ccc

EDIT: the echo aaa,bbb,ccc is to simulate a command, I need to parse the output of a command

Upvotes: 0

Views: 66

Answers (2)

Compo
Compo

Reputation: 38579

Here's some examples for you to peruse, (each, IMO, progressively more robust):

@Echo Off
SetLocal EnableExtensions EnableDelayedExpansion
Set "i=0"
For %%G In (aaa,bbb,ccc) Do (
    Set /A i+=1
    Echo !i! %%G
)
Pause
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "i=0"
For %%G In (aa!a,b!bb,!ccc!) Do (
    Set /A i+=1
    SetLocal EnableDelayedExpansion
    For %%H In (!i!) Do Endlocal & Echo %%H %%G
)
Pause
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "i=0"
For %%G In ("aa|a","b&bb","!ccc!") Do (
    Set /A i+=1
    SetLocal EnableDelayedExpansion
    For %%H In (!i!) Do Endlocal & Echo %%H %%~G
)
Pause

[Edit /]
Based upon your poor modification and lack of supporting information, the following is all I'm currently willing to offer in return:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "Result="
For /F Delims^=^ EOL^= %%G In ('Echo aaa,bbb,ccc') Do Set "Result=%%G"
If Not Defined Result GoTo :EOF
Set "i=0"
For %%G In (%Result%) Do (
    Set /A i+=1
    SetLocal EnableDelayedExpansion
    For %%H In (!i!) Do Endlocal & Echo %%H %%G
)
Pause

Upvotes: 1

Squashman
Squashman

Reputation: 14290

Based on your limited information this is could fix your problem.

@echo OFF
SETLOCAL EnableDelayedExpansion
SET /A i=0

FOR /F "tokens=1-3 delims=," %%G IN ('"echo aaa,bbb,ccc"') DO (
    SET /A i+=1
    echo !i! %%G
    SET /A i+=1
    echo !i! %%H
    SET /A i+=1
    echo !i! %%I
)

Upvotes: 0

Related Questions