0

I will need some help to understand a strange behaviour I want to loop through a directory to find which sub-directories are ending with some specific characters. I wrote this to test:

@ECHO.
setlocal EnableDelayedExpansion 
set Dir=C:\test
for /f "tokens=*" %%I in ('dir %Dir% /ad /b') do (
set V1=%%I
set V2=!V1!
set V3=%V1%
set V4=%V1:~-4%
set V5=!V1:~-4!
)
endlocal

The result is:

C:>test


C:>setlocal EnableDelayedExpansion

C:>set Dir=C:\test

C:>for /F "tokens=*" %I in ('dir C:\test /ad /b') do (
set V1=%I
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011 - Copie
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011 - Copie (2)
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011 - Copie (3)
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011 - Copie (4)
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011 - Copie (5)
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011 - Copie (6)
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011 - Copie (7)
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>(
set V1=dir1_011 - xxx
 set V2=!V1!
 set V3=
 set V4=~-4
 set V5=!V1:~-4!
)

C:>endlocal

C:>

I could never get the end of the directory name even if i'm using EnableDelayedExpansion

May be someone has some explanation ?

2 Answers 2

2

Your lines using delayed expansion are working, but you don't have anything in your output to show it. You have ECHO ON, but the line is echoed before the delayed expansion takes place, so you can't see the result. Try adding lines like

echo V1=!V1!
echo V2=!V2!
etc.

within your loop to see the results of your delayed expansion assignments.

Of course the assignments using normal expansion are not working within the loop, which is why delayed expansion was invented.

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

Comments

1

You have to use variables like !var! and not %var% when inside a loop and when using delayed expansion.

Test this:

@echo off
setlocal EnableDelayedExpansion 
set Dir=C:\test
for /f "delims=" %%I in ('dir %Dir% /ad /b') do (
set V1=%%I
set V2=!V1!
echo !v2!
echo !v2:~-4!
)
endlocal
pause

1 Comment

I think the OP already knows about delayed expansion, but doesn't understand why the ECHOed statements do not show the expanded value. See my answer.

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.