Khushbu Agrawal
Khushbu Agrawal

Reputation: 11

variable reset in command line

My requirement is to find a latest file name in a folder based on the last modified date. I need a command in single line. I am executing below command.

@echo off && (for /f "tokens=*" %a in ('dir /b/a-d/od/t:w *.*') do set newestfile=%a) && @echo on && echo %newestfile%

this is giving me correct result but the only issues that if I modify another file...then also it shows me previous filename. I have read that local variable doesn't get reset that's why it shows old/previous file.

I have written logic in batch script. that's working as expected but in command line its giving me weird result.

Upvotes: 1

Views: 224

Answers (2)

dbenham
dbenham

Reputation: 130899

Here is a much simpler solution that avoids use of any environment variable.

Simply reverse the sort order so the newest file is listed first, and then terminate the loop. This can be done by launching a new cmd.exe process that runs a FOR /F loop that processes the DIR command. The loop echoes the first listed file, and then EXITs the process. I believe this is both the simplest and the most efficient method.

cmd /d /c for /f "eol=: delims=" %a in ('dir /b/a-d/o-d/t:w') do @echo %a^&exit

It is possible to use a variable without delayed expansion - IF DEFINED does not require delayed expansion.

set go=1&for /f "eol=: delims=" %a in ('dir /b/a-d/o-d/t:w') do @if defined go echo %a&set "go="

You could use FINDSTR to get the first listed file. If you don't care about the 1: prefix, you can use:

dir /b/a-d/o-d/t:w | findstr /n "^" | findstr "^1:"

Simply process with a FOR /F loop if you want to remove the prefix:

for /f "delims=: tokens=1*" %a in ('dir /b/a-d/o-d/t:w ^| findstr /n "^" ^| findstr "^1:"') do @echo %b

Upvotes: 2

npocmaka
npocmaka

Reputation: 57282

For this you need delayed expansion. As this is called from command line you'll need a new instance of cmd with /v:on argument:

cmd /v:on /c "(for /f "tokens=*" %a in ('dir /b/a-d/od/t:w *.*') do @set newestfile=%a) && @echo !newestfile!"

Upvotes: 0

Related Questions