Reputation: 11
I have this simple batch script:
@echo off
dir /o-d "K:\DIR\DIR\*.exe" > "D:\Logs\Files.txt"
which displays all the files in a txt, by date.
My question is: how can I get this to show me only the last file by date and not all files in that specific directory?
Thanks in advance.
Upvotes: 1
Views: 1263
Reputation: 4695
to get only the file name of the latest file
@echo off
for /f "tokens=*" %%x in ('dir /b /o-d "K:\DIR\DIR\*.exe"') do (
echo %%x
exit /b 0
)
Upvotes: 0
Reputation: 3685
@echo off
setlocal
for /f "delims=" %%F in ('dir /b /o-d') do (
set file=%%~nxF %%~tF
goto display
)
:display
echo %file%
Notes:
for
and 'decrypt' %%~nxF %%~tF
, read for
help (help for
from command line) goto
is there just to break the loop after first (latest) file/dir. batch.bat >myFile
) or last echo (echo %file% > myFile
)dir /a-d
to match files only.Upvotes: 1
Reputation: 32920
If you're only interested in the last file, you can do this:
@echo off
for /f "tokens=*" %%a in ('dir /o-d "K:\DIR\DIR*.exe" ^| findstr /C:"/"') do set last=%%a
echo %last%
This displays only the last filename from the output of the dir
command. If you want to redirect it to a file, replace echo %last%
with:
echo %last% > "D:\Logs\Files.txt"
If you're interested in the first file, you need to slightly alter the code to this:
for /f "tokens=*" %%a in ('dir /o-d "K:\DIR\DIR*.exe" ^| findstr /C:"/"') do set first=%%a && goto Done
:Done
echo %first%
Again, if you're interested in redirecting it to a file, replace echo %first%
with:
echo %first% > "D:\Logs\Files.txt"
Upvotes: 2
Reputation: 4470
I think it is not possible using shell/batch commands.
you may write another program to pick first line of Files.txt file
Upvotes: 0