3

I'm developing a batch file in Windows (7) and am attempting to use a for loop to find the latest version of a file and place the file name into a variable. I'm using the following code:

FOR /F %%i IN ('DIR "Test*.xlsx" /B /-D') DO set file_name=%%i

The loop works, but the problem is my file name has spaces in it and the loop is only copying the first word in the file name into the variable. Ex. File name is "Test 2016-12-01.xlsx" and the variable i is set to "Test" without the 2016...

Is there a way to capture the whole file name instead of just the first word?

1
  • for /f "tokens=* delims=" %%i ... See for /? for help. also set "file_name=%%i" is best practice Commented Dec 5, 2016 at 16:37

1 Answer 1

1
FOR /F "delims=" %%i IN ('DIR "Test*.xlsx" /B /OD /A-D') DO set "file_name=%%i"

or

FOR /F "delims=" %%i IN ('DIR "Test*.xlsx" /B /O-D /A-D') DO set "file_name=%%i"&goto nextstep
:nextstep

The "delims=" removes delimiters which default to include Space - this is why the name is terminated at the space - Space is a delimiter and thedefault for tokens is 1 so only the first token is assigned, delimited by the default Space

The dir switch /-d makes no sense; it reacts the same way as /d which lays out the directory list in columnar form and is overridden by the /b.

/a-d suppresses directorynames from the list.

/od shows the directorylist in date-order and /o-d in reverse-date order. Hence, the first snippet assigns each filename in turn to the variable and after the for block, the variable contains the last name assigned which will be the filename with the latest date.

The second block forcibly jumps out of the for loop when the first filename is assigned, so if the sorting is accomplished with /o-d then the latest is listed and hence assigned first.

The advantage of the second form is that it is a lot faster, especially if the directory contains a great number of files.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This worked perfectly. Very much appreciated .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.