windows batch files: setting variable in for loop

后端 未结 3 1685
夕颜
夕颜 2020-12-01 06:37

I have a number of files with the same naming scheme. As a sample, four files are called \"num_001_001.txt\", \"num_002_001.txt\", \"num_002_002.txt\", \"num_002_003.txt\"

3条回答
  •  离开以前
    2020-12-01 06:51

    Your problem is that the variable get replaced when the batch processor reads the for command, before it is executed.

    Try this:

    SET temp=Hello, world!
    CALL yourbatchfile.bat
    

    And you'll see Hello printed 5 times.

    The solution is delayed expansion; you need to first enable it, and then use !temp! instead of %temp%:

    @echo off
    SETLOCAL ENABLEDELAYEDEXPANSION
    FOR /R %%X IN (*.txt) DO (
      set temp=%%~nX
      echo directory !temp:~0,7!
    )
    

    See here for more details.

提交回复
热议问题