21

I have a list of zip files with date and time appended like yyyymmdd_hhmmss_Demos.zip. Now how to get the most recently added zip file in the source dir. I need to copy this file in the target using copy command.

I found some info about forfiles, but do not have an idea on how to get it done for seconds.

1

4 Answers 4

38

You can use

pushd D:\a
for /f "tokens=*" %%a in ('dir /b /od') do set newest=%%a
copy "%newest%" D:\b
popd
6
  • for the sake of simplicity i just put a set of text files in a folder a and made target as folder b and hence wrote this command for /f "tokens=*" %%a in ('dir D:\a /b /od') do set newest=%%a copy "%newest%" D:\b But this does not work for me.. what is wrong
    – azzaxp
    Commented Jul 18, 2012 at 11:42
  • 1
    @azzaxp Try my updated answer. It seems the directory was the problem for some reason, I'm not sure why.
    – Bali C
    Commented Jul 18, 2012 at 12:02
  • dir /b /od will list also subdirs, if any. I think you should exclude them using /a-d switch (unless of course OP wants to copy subdirs also)
    – wmz
    Commented Jul 18, 2012 at 12:05
  • 1
    @wmz No, it doesn't. The /s switch lists subfolders, try it and see :)
    – Bali C
    Commented Jul 18, 2012 at 12:09
  • sorry wrong wording. I meant that it will include names of any subdirs, not their contents (for this as you correctly stated you would need /s). So it will find newest file or directory
    – wmz
    Commented Jul 18, 2012 at 12:28
2
set Path="D:\hello\abc\old"
for /f "tokens=*" %%a in ('dir /A:-D /B /O:-D /S %Path%') do set NEW=%%a&& goto:n 
:n
echo %NEW%
0
1
pushd \\ryap\CONTROL_DATOS
for /f "tokens=*" %%a in ('dir \\ryap\CONTROL_DATOS /b /od') do set newest=%%a
Xcopy/Y "\\ryap\CONTROL_DATOS\%newest%" "D:\TXT_SOURCES\"
popd
1
  • 4
    Pasting some code without explaining what it does is not so useful. Can you add a description?
    – SaeX
    Commented Jan 5, 2016 at 19:32
0

Below snippet will extract the date and customize as per your needs

for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
     set dow=%%i
     set month=%%j
     set day=%%k
     set year=%%l
)
:: Pad digits with leading zeros e.g Sample_01-01-21.csv
    set yy=%year:~-2%
    set datestr=%day%-%month%-%yy%

Alternate way:

set datestr=%date:~0,2%-%date:~3,2%-%date:~6,2%

Not the answer you're looking for? Browse other questions tagged or ask your own question.