Search code examples
batch-filebackupbatch-rename

Windows batch script to copy newest files with partial names


I have a backup program that saves .bak files into a folder which it rotates on a weekly basis automatically.

The files are given given names like this:

DB_Live_19052015.bak
DB_Test_19052015.bak
DB_Live_18052015.bak
DB_Test_18052015.bak

The backup program doesn't allow me to edit these names and I actually don't want it to.

What I do need is to be able to copy the newest file of each set DB_Live_XXXXXXXX.bak & DB_Test_XXXXXXXX.bak and rename them to drop the date so I end up with files like this for DR:

dr/DB_Live.bak
dr/DB_Test.bak

This would be overwritten each time the script was run.

No I can copy the latest file in a folder and rename it using scripting but I cannot get my head round how to

  • A. get the set of latest files (multiple)
  • B. rename these files based on their original names to drop only the on the end.

What I am expecting to have to do is the following:

  1. copy the latest files to a dr folder
  2. get the file names for each file
  3. rename the files and overwrite anything already there with that name

I'm going to be adding this scripting into the backup program so it runs when the backup has finished.

The reason for these files is so I can RSYNC them off site without sending the whole file every time.


Solution

  • @echo off
        setlocal enableextensions disabledelayedexpansion
    
        set "source=%cd%\source"
        set "target=%cd%\target"
    
        for %%a in (DB_Live DB_Test) do (
            set "first=1"
            for /f "delims=" %%b in ('
                dir /a-d /tw /o-d /b "%source%\%%a_*.bak"
            ') do if defined first (
                set "first="
                copy /b /y "%source%\%%~b" "%target%\%%a%%~xb"
            )
        )
    

    For each set of files, execute a dir command in reverse modified date order. In this list the first file is the last modified. Copy this file to the target overwritting the existing file (if present).