Search code examples
windowsbatch-filexcopycopyingrenaming

Copying multiple files and adding date to the name bat


I have to make .bat file who does this:

Copies from O:\siirto all files that name starts with "ls". To C:\siirto. And the name of the output would be same as in the source. But it would add current date to the end of file name.

I tried following just for test and it didnt work of course :D. But it propably explains better what im trying to do than explanation above.

echo off
xcopy O:\siirto\ls* C:\siirto\ls%date.txt
pause

Of course its not working. But is that possible to do with one .bat file. Or do i have to do all ls.txt-files their own .bat-files or lines.

Like one for LS1.txt, LS2.txt LS3.txt

echo off
xcopy O:\siirto\LS1.txt C:\siirto\ls1%date
pause

I have no idea how the %date should add to code and does it need something else to code also?

Im still on child shoes in programming...

thanks


Solution

  • you need to combine the iteration over the files with the FOR command and the %DATE% environment variable. Read HELP FOR, paying attention to the %~ expansion syntax, and try the following code.

    for %%a in (o:\siirto\ls*) do (
       echo copy "%%a" "c:\siirto\%%~na-%date%%%~xa"
    )
    

    after careful testing, remove the echo command.


    You might generalize a bit your code, by moving some configurable information out of the loop

    set src=o:\siirto\ls*
    set dest=c:\siirto
    for %%a in (%src%) do (
      copy "%%a" "%dest%\%%~na-%date%%%~xa"
    )
    

    and, in case the %date% command returns invalid characters, read my accepted answer to this SO question Batch script date into variable and then change the variable to the one that contains the current date with the appropiate format.