1

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.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
  • 1
    you've got a [delayed expansion](http://stackoverflow.com/a/30284028/2152082) problem. So `%newestfile%` is always "one step behind" – Stephan Dec 30 '15 at 13:03

2 Answers2

2

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
dbenham
  • 127,446
  • 28
  • 251
  • 390
0

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!"
npocmaka
  • 55,367
  • 18
  • 148
  • 187
  • I want basically latest file and want to see the content of that file. I am running below command cmd /v:on /c "(for /f "tokens=*" %a in ('dir /b/a-d/od/t:w *.*') do @set newestfile=%a) && type !newestfile!" so in my local system (windows 7) it works all fine but in remote system (windows 2003 standard R2) its giving error "specified file dint find". I have to execute this in windows 2003 Standard R2. How can I achieve that – Khushbu Agrawal Dec 31 '15 at 11:31