Andrew
Andrew

Reputation: 293

Batch File: How can I extract the substring of a value from a FOR loop using an index variable?

I have a text file that I read with a FOR loop. For every line, I want to extract a substring starting from an INDEX parameter. The code I have is as follows:

@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /f "delims=" %%a IN (cases.txt) DO (
    SET INDEX=3
    SET LINE=%%a

    ECHO !LINE:~!INDEX!!
)
GOTO :EOF

The ECHO simply attaches the word "INDEX" at the end of each line. Is it possible to accomplish what I am trying to do?

Regards,

Andrew

Upvotes: 2

Views: 687

Answers (1)

npocmaka
npocmaka

Reputation: 57262

@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /f "delims=" %%a IN (cases.txt) DO (
    SET INDEX=3
    SET LINE=%%a
    for %%# in (!INDEX!) do echo  !LINE:~%%#!

)
GOTO :EOF

As you asked a more broad question here , you can my more broad answer there with more techniques and explanations :-)

What happens to your code?

the parser checks for !! and !line:~! variables and as they do not exist the only one thing left for echo is INDEX. With delayed expansion you cannot use nested variables - you can with call , but this will harm your performance

Upvotes: 1

Related Questions