For loop and delims in batch files

Can someone please help me understand command file syntax

IF "%INPUT_PATH%"=="" ( echo Searching for latest test results in: %TEST_RESULTS% FOR /F "delims=" %%i in ('dir /O-D /B "%TEST_RESULTS%\*.trx"') DO ( SET INPUT_PATH=%TEST_RESULTS%\%%~ni GOTO :DoneInputPath
) )

I get that it first checks if INPUT_PATH variable is empty and if it is empty then enters into an inner for loop, I am lost otherwise

specifically

  1. FOR /F "delims=" %%i in ('dir /O-D /B "%TEST_RESULTS%\*.trx"')
  2. SET INPUT_PATH=%TEST_RESULTS%\%%~ni
1

2 Answers

Most of the information you need is available in the built-in help, though it can be daunting if you are new to batch programming. For example, type HELP FOR or FOR /? from the command prompt to get help on the FOR command.

Explanation:

FOR /F "delims=" %%i in ('dir /O-D /B "%TEST_RESULTS%\*.trx"') ...

The DIR command lists all of the *.TRX files within the %TEST_RESULTS% path. The /B option gives the brief format (file names only). The /O-D option sorts the files by last modified date descending (newest first).

The FOR /F command has three modes, depending on the format of the IN() clause. The fact that the IN() clause is enclosed in single quotes means that FOR /F treats the contents as a command, and processes the output of the command, one line at a time. The "delims=" option means do not parse into tokens (preserve each entire line). So each line is iteratively loaded into the %%i variable. The %%i variable only exists within the context of the FOR command.

SET INPUT_PATH=%TEST_RESULTS%\%%~ni

I think you know what most of this command does. The only "unusual" aspect is the %%~ni syntax. That syntax expands the value of %%i into the base file name only, without any extension.

GOTO :DoneInputPath

The GOTO causes the FOR loop to abort after the first iteration. This means that INPUT_PATH will be set to the name of the most recently modified *.trx file, since it sorted to the top.

If the GOTO were not there, then the end result would be the oldest *.trx file instead.

try this, explanation is in the comment:

IF NOT DEFINED INPUT_PATH ( echo Searching for latest test results in: %TEST_RESULTS% REM dir /OD means older files first and the youngest last, the last remains in INPUT_PATH; use "%%~nxi" for file name + file extension FOR /F "delims=" %%i in ('dir /OD /B "%TEST_RESULTS%\*.trx"') DO SET "INPUT_PATH=%TEST_RESULTS%\%%~ni"
)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like