windows batch files: setting variable in for loop

后端 未结 3 1692
夕颜
夕颜 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 07:10

    Another solution is to move the body of the for loop to a subroutine and call it.

    @echo off
    FOR /R %%X IN (*.txt) DO call :body %%X
    goto :eof
    
    :body
    set temp=%~n1
    echo directory %temp:~0,7%
    goto :eof
    

    Why do this? One reason is that the Windows command processor is greedy about parentheses, and the results may be surprising. I usually run into this when dereferencing variables that contain C:\Program Files (x86).

    If the Windows command processor was less greedy, the following code would either print One (1) Two (2) or nothing at all:

    @echo off
    if "%1" == "yes" (
       echo 1 (One)
       echo 2 (Two)
    )
    

    However, that's not what it does. Either it prints 1 (One 2 (Two), which missing a ), or it prints 2 (Two). The command processor interprets the ) after One as the end of the if statement's body, treats the second echo as if it's outside the if statement, and ignores the final ).

提交回复
热议问题