For loop and delimits in batch files

Can someone please help me understand the syntax of the batch file

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

I realized that it first checks to see if the INPUT_PATH variable is empty and if it is empty and then enters the inner for loop, I get lost otherwise

in particular

  • FOR /F "delims=" %%i in ('dir /OD /B "%TEST_RESULTS%\*.trx"')
  • SET INPUT_PATH=%TEST_RESULTS%\%%~ni
+4
source share
2 answers

Most of the information you need is available in the on-line help, although this can be a daunting task if you are new to batch programming. For example, enter HELP FOR or FOR /? from the command line to get help for the FOR command.

Explanation:

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

The DIR command lists all *.TRX files in the %TEST_RESULTS% path. The /B option gives a short format (file names only). The /OD switch sorts files by last modified date in descending order (most recent 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 that you do not parse tokens (save every whole line). Thus, each line is iteratively loaded into the variable %%i . The variable %%i exists only in the context of the FOR command.

 SET INPUT_PATH=%TEST_RESULTS%\%%~ni 

I think you know what most of this team does. The only "unusual" aspect is the syntax %%~ni . This syntax extends the value of %%i only in the name of the base file without the extension.

 GOTO :DoneInputPath 

GOTO causes the FOR loop to break after the first iteration. This means that INPUT_PATH will be set to the name of the last modified *.TRX file, since it is sorted at the top.

If there was no GOTO, the end result would be the oldest *.TRX file.

+5
source

try this, explanation in 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" ) 
0
source

Source: https://habr.com/ru/post/1497817/


All Articles