dakky21
dakky21

Reputation: 19

Windows batch rename by date created

There might be a better approach, but my file names are in this format: name_Sat Apr 11 031806 2015.mp3 (with the spaces)

In order to merge them I need to put them in order, ie. 001, 002, 003. etc.

I currently use this code to move them to a folder on the end of the each day:

@echo off

for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x

:: variables

set SRCFOLDER=C:\srcfolder
set DESTFOLDER=C:\destfolder
set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%
set backupcmd= /MOV

robocopy "%SRCFOLDER%" "%DESTFOLDER%\%today%" %backupcmd%

That produces a new folder named YYYY-MM-DD and the files are put there. I will merge them with another program, but I need to have them in a sequence by the time they were created (the time in the filename).

So the question is - How do I do that?

Thanks

Upvotes: 1

Views: 1076

Answers (1)

Parag Doke
Parag Doke

Reputation: 863

If I understand correctly, files are moved to a folder based on the date when the script ran ... and not what date appears in the file name. However, you state that the files in that folder are all created on the same day and already sorted. Try adding this (untested) to your current script:

setlocal EnableDelayedExpansion
set /A Counter=0
REM Since you need folders numbered as 001, we need some padding
set /A PaddingNumber=1000
for /f "delims=" %%A in ('dir /b /a-d "%DESTFOLDER%\%today%\*"') do (
    set /A Counter=!Counter!+1
    set /A SequenceNumber=%PaddingNumber%+!Counter!
    set FileSuffix=!SequenceNumber:~1!
    ren "%%~fA" "%%~nA-!FileSuffix!%%~xA"
)

You can choose whether to have the FileSuffix at the start or end.

Upvotes: 1

Related Questions