Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

batch file - How to set a variable inside a loop for /F

I made this code

dir /B /S %RepToRead% > %FileName%

for /F "tokens=*" %%a in ('type %FileName%') do (
    set z=%%a
    echo %z%
    echo %%a
)

echo %%a is working fine but echo %z% returns "echo disabled".

I need to set a %z% because I want to split the variable like %z:~7%

Any ideas?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two methods to setting and using variables within for loops and parentheses scope.

  1. setlocal enabledelayedexpansion see setlocal /? for help. This only works on XP/2000 or newer versions of Windows. then use !variable! instead of %variable% inside the loop...

  2. Create a batch function using batch goto labels :Label.

    Example:

    for /F "tokens=*" %%a in ('type %FileName%') do call :Foo %%a
    goto End
    
    :Foo
    set z=%1
    echo %z%
    echo %1
    goto :eof
    
    :End
    

    Batch functions are very useful mechanism.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...