script em lote para loop e se a instrução não estiver interagindo corretamente

2

Para fins de arquivamento, tenho um diretório cheio de arquivos chamados note_1.txt , note_3.txt , note_4.txt etc. Estou escrevendo um script para encontrar o maior número N entre esses arquivos e renomeio um novo arquivo note.txt para note_N+1.txt .

Estou usando um loop de lote pela primeira vez e não consigo funcionar corretamente. Eu tentei substituir % por ! , mas não tenho certeza se entendi como funciona.

SETLOCAL ENABLEDELAYEDEXPANSION
SET "maxfile=1"
for /f %%i in ('dir /b note_*.txt') do (
    SET archivename=%%~ni
    SET archivenumber=%archivename:~5%
    if %archivenumber% GTR %maxfile% SET /a maxfile=%archivenumber%+1
)
echo %maxfile%
ENDLOCAL
    
por Antoine 11.09.2018 / 01:31

1 resposta

1

Acabei de adicionar o ! às variáveis dentro do FOR loop para garantir que elas sejam todas expandidas no tempo de execução dentro do loop para garantir que novos valores definidos sejam lidos de acordo para ajudar a obter o valor% !maxfile! final conforme cada iteração de loop.

Além disso, adicionei o CD /D "%%~F0" à linha acima do início do ciclo FOR para garantir que o diretório seja alterado para o diretório que o script reside, pois você não está explicitamente especificando o diretório em seu exemplo de comando, mas eu adicionou um script de exemplo explícito abaixo também.

Script em lote (implícito)

SETLOCAL ENABLEDELAYEDEXPANSION
SET "maxfile=1"
cd /d "%%~F0"
for /f %%i in ('dir /b note_*.txt') do (
    SET "archivename=%%~ni"
    SET "archivenumber=!archivename:~5!"
    if !archivenumber! GTR !maxfile! SET /a maxfile=!archivenumber!+1
)
echo !maxfile!
ENDLOCAL

Script em lote (explícito)

SETLOCAL ENABLEDELAYEDEXPANSION
SET "maxfile=1"
SET "srcdir=C:\Folder\Path"
for /f %%i in ('dir /b "%srcdir%\note_*.txt"') do (
    SET "archivename=%%~ni"
    SET "archivenumber=!archivename:~5!"
    if !archivenumber! GTR !maxfile! SET /a maxfile=!archivenumber!+1
)
echo !maxfile!
ENDLOCAL

Mais recursos

  • EnableDelayedExpansion

    Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command.


    When delayed expansion is in effect, variables can be immediately read using !variable_name! you can also still read and use %variable_name% that will show the initial value (expanded at the beginning of the line).

  • Para

    Variable Substitutions (FOR /?)

    In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path namey
    
por 11.09.2018 / 03:03

Tags