0
votes

I am trying to substring a string from a text file stored in a variable "user" each loop the substring parameters is increment so that i can process next data. However, the variable parameter "Inc" that i am giving to the sub-string command doesn't seem to update its value within the for loop. I already used the SETLOCAL EnableDelayedExpansion but with no success. Below is piece of the code: Note: "Inc" is defined previously as integer and have initial value of 21. I expect that each loop the variable 'test' should be: substring of "user" 41,20 .. 61,20 .. 81,20 .. and so on.. But the problem is that for the all 12 loops "Inc" in the substring command keeps the value 41 and never increases even though the echo Inc command below shows that it does increase. Appreciate your help in this issue.

:setfunc
echo. >>parsed.txt

IF !inew!==48 (
    for /L %%g IN (1,1,12) do (
        Set test=!user:~%Inc%,20!
        echo !test!
        echo !user:~%Inc%,20! >>parsed.txt
        Set /a Inc=!Inc!+20
        echo count=%%g
        echo Inc=!Inc!
    )
1
You need another layer of expansion, possibly Call Set "test=%%user:~!Inc!,20%%" and Call Echo %%user:~!Inc!,20%%. BTW, I have edited your question code to include indentation, this helps to highlight that your code has a missing closing parenthesis.Compo

1 Answers

0
votes

The problem is the immediate %-expansion you are using for a variable (Inc) whose value is changing in the same block of code, namely the for /L loop.

To solve this you need another layer of variable expansion. There are the following options:

  1. Add another for loop and use its meta-variable expansion, which happens before delayed expansion:

    > "parsed.txt" (
        for /L %%g in (1,1,12) do (
            for %%i in (!Inc!) do (
                echo(!user:~%%i,20!
                set /A "Inc+=20"
            )
        )
    )
    

    This is the preferred method in my opinion as it is the fastest one.

  2. Use call, which initiates another %-expansion that happens after delayed expansion:

    > "parsed.txt" (
        for /L %%g in (1,1,12) do (
            call echo(%%user:~!Inc!,20%%
            set /A "Inc+=20"
        )
    )
    

    The doubled %-signs are needed to escape the first %-expansion phase and literally leave % behind.

  3. Since Inc is purely numeric (or more precisely, a signed 32-bit integer), you could also use for /F together with set /A:

    > "parsed.txt" (
        for /L %%g in (1,1,12) do (
            for /F %%i in ('set /A "Inc"') do (
                echo(!user:~%%i,20!
                set /A "Inc+=20"
            )
        )
    )
    

    This works since set /A is executed in cmd-context rather than in batch-context when run by for /F, where it returns its (final) result, which in turn is then captured by for /F.

    This is not a quite practical approach in this situation here, though it might be considered when there is a for /F loop involved anyway.