1

The following code is assumed to replace the col3 substring in the variable dir with the value of the variable var in every iteration, but it fails to do so. Does anyone know what is wrong with this code?

code:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET dir=col1 col2 col3 col4 col5 col6 col7 col8
FOR /L %%i IN (1,1,5) DO (
SET var=v%%i
SET dir=!dir:col3=%var%!
ECHO !dir!
)
PAUSE

output:

col1 col2  col4 col5 col6 col7 col8
col1 col2  col4 col5 col6 col7 col8
col1 col2  col4 col5 col6 col7 col8
col1 col2  col4 col5 col6 col7 col8
col1 col2  col4 col5 col6 col7 col8

desired output:

col1 col2 v1 col4 col5 col6 col7 col8
col1 col2 v2 col4 col5 col6 col7 col8
col1 col2 v3 col4 col5 col6 col7 col8
col1 col2 v4 col4 col5 col6 col7 col8
col1 col2 v5 col4 col5 col6 col7 col8
1
  • 2
    you need double delayed expansion: for %%V in (!var!) do SET "dir=!dir:col3=%%V!" Commented Jun 7, 2020 at 6:48

1 Answer 1

2

after hours of searching for this problem, I found out that changing the line

SET dir=!dir:col3=%var%!

to

SET dir=%dir:col3=!var!%

solved the issue.

Sign up to request clarification or add additional context in comments.

3 Comments

No, this is simply wrong, you need to delay expansion since you are in a loop, and you must expand the inner variable (var) before the outer one (dir)! A possible way is: call set "dir=%%dir:col3=!var!%%"
Sorry, I have to withdraw my previous comment, since in your particular situation your answer actually does provide the solution (accidentally?), because: For every loop iteration, dir is expanded to its original value due to immediate (%-)expansion, with col3 replaced by the literal string !var!; delayed expansion then does the rest and expands !var! by its current value…
My code suggestion however correctly replaces col3 with v1 in the first loop iteration; but for every further iteration, dir expandes to its modified value due to delayed expansion, so there is no more col3 in the string, hence the same value as for the first iteration becomes returned again. Sorry for drawing a hasty and mistaken conclusion!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.