0

I am trying to use the variable outside of the For loop. The echo inside the loop gives the result as expected. it is not working when i echo the variable outside of the loop. below is the script-

'SETLOCAL ENABLEDELAYEDEXPANSION
SET x=0
FOR /f "tokens=*" %%a in ('dir "%InPath%*_Out.txt" /b') DO (
SET /a x+=1& SET /a cnt+=1& SET Fname%x%=%%a& SET FDate%x%=!Fname%x%:~0,8!
ECHO %x% !cnt! !Fname%x%! !Date%x%!
)

set z=3
ECHO !FDate%z%! `
2
  • So - what is the routine showing, what is the result you see and what is the result you expect? Commented Jun 20, 2014 at 8:44
  • Full details on array management in Batch files are given at: stackoverflow.com/questions/10166386/… Commented Jun 20, 2014 at 9:35

1 Answer 1

1

What you have here is a bad interpretation of what you see. The for loop does not work (determined from what you are trying to do outside of the for loop).

This

Fname%x%=%%a
SET FDate%x%=!Fname%x%:~0,8!

is executed inside the loop. There is no delayed expansion over the x variable, so, changes in the value of the variable are not visible inside the for loop and all the iterations are executed as

Fname0=%%a
SET FDate0=!Fname0:~0,8!

So, your claim that the code in the for loop works is not correct. Since it is not working, the code outside the for will not work as intended

You need something like

FOR /f "tokens=*" %%a in ('dir "%InPath%*_Out.txt" /b') DO (
    SET /a x+=1
    SET /a cnt+=1
    SET "Fname!x!=%%a"
    for %%b in (!x!) do (
        SET "FDate!x!=!Fname%%b:~0,8!"
        ECHO !x! !cnt! !Fname%%b! !FDate%%b!
    )
)

This will properly populate the "arrays" so your code outside the for loop will work

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

Comments

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.