Marshall Tigerus
Marshall Tigerus

Reputation: 3764

Batch file to copy only the one newest file

I'm trying to figure out a good way of doing this:

  1. Files are created in an archive folder and we need to copy them to an FTP folder
  2. The FTP folder does not retain files (the vendor picks them up and removes them)
  3. Relevant files follow the same naming convention, but they are not the only files in either directory (e.g. namingconvetion_date is the filename)
  4. I only want the one latest file matching the naming convention moved

What we are trying to avoid is a "bug" where all files in the archive that match the naming convention get moved, which causes our vendor to print old files.

The current copy command uses namingconvention*, which doesn't work because of the above bug.

Sample file formatting: Vendor_MP_Summary02162015103001.csv So it's MMDDYYYYHHMMSS date format

Easiest way to determine the latest would be by modified by on the files.

Upvotes: 1

Views: 4374

Answers (1)

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f %%a in ('
        dir /o-d /b /a-d "Vendor_MP_Summary*.csv" 
        ^| (set /p "file=" ^& call echo("%%file%%"^)
    ') do set "lastFile=%%~a"

    echo %lastFile%

Or

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f %%a in ('
        dir /o-d /b /a-d "Vendor_MP_Summary*.csv" 
    ') do set "lastFile=%%~a" & goto :found

:found
    echo %lastFile%

In both codes, the list of files is retrieved inside a for /f command with the help of a dir command to list the matching files in descending date order, so the newer file is the first one. To only retrieve this line from the full list

  • in the first code a pipe to a set /p command is used, so only one line is retrieved from the list of files and returned to the for /f

  • in the second case the full list is returned to the for /f and after retrieving the first line, a goto is used to skip processing the rest of the list

Upvotes: 2

Related Questions