zkvvoob
zkvvoob

Reputation: 466

Batch copy, rename and overwrite newest file from one dir to another

I've found a way to copy the newest file in a directory to another one, using a batch file in Windows. However, I would like your help in figuring out how to then rename the copied file and overwrite old ones.

@echo off
set source="D:\Backup"
set target="D:\tmp"

FOR /F "delims=" %%I IN ('DIR %source%\*.csv /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & echo %%I & GOTO :END
:END

The idea is that the source Backup folder contains incremental backups with date and time added. I'd like the result to have a constant name, say raw.csv so that I can operate with it in Excel.

Thank you!

Upvotes: 0

Views: 2407

Answers (1)

MC ND
MC ND

Reputation: 70923

@echo off
    setlocal enableextensions disabledelayedexpansion 

    set "source=D:\Backup"
    set "target=D:\tmp"

    FOR /F "delims=" %%I IN ('
        DIR "%source%\*.csv" /A-D /O-D /B
    ') DO COPY "%source%\%%I" "%target%\raw.csv" & echo %%I & GOTO :END

:END

As commented, just include the target name in the copy operation.

I've also changed your variable definitions. Unless there is a good reason for doing it, when working with paths it is better not to include the quotes in the variable values (later it is harder to work with them). Just quote the assignment (to prevent problems with special characters or final spaces) and later, when required, quote the file system reference.

set "source=d:\backup"
    ^................^

set "target=D:\tmp"
    ^.............^

dir "%source%\*.csv"
    ^..............^

COPY "%source%\%%I" "%target%\raw.csv"
     ^............^ ^................^

Upvotes: 2

Related Questions