Search code examples
windowsbatch-filebatch-rename

Rename all files in a directory by adding [a-z][1-9] in front of each file


I am having a problem with particular device where i transfer files to. This device is not capable of sorting files for use, it always uses ascending a-z sorting. That creates a problem where i need files to be "processed" by creation date instead.

That said, I came up with an idea to have script in form of .bat file i.e. I would put that script into directory where all the files are and simply run it.

The idea is that script would need to iterate over all the files, the only requirement would be that it needs to sort files descending by creation date before it starts. Then during iteration it would need to rename each file for the purpose of adding letters and digits in front.

The result would be following:

a1-file-name.dat // created 5 min ago
...
a2-file-name.dat // created 10 min ago
...
a9-file-name.dat // created 15 min ago
b1-file-name.dat // created 20 min ago
...
b6-file-name.dat // created 25 min ago
...
b9-file-name.dat // created 30 min ago

I have zero experience and know-how in case of windows scripts, so i would ask for help with this one.

Couple of facts:

  • I can only add up to 6 characters to every file name
  • I cannot add 0 digit to a file name

Solution

  • You could use something like this code. The only problem is if the source Folder has more than 234 files cause thats all [a-z][1-9] allows 26 * 9 = 234 possibilities. My Video.

    @echo off
    SetLocal EnableDelayedExpansion
    set Source=%userprofile%\desktop\Test
    set Letters=abcdefghijklmnopqrstuvwxyz
    set Numbers=123456789
    set /a CountL=0
    set /a CountN=0
    
    for /f "Delims=" %%a in ('dir /b /o-d /tc /s /a-d "%Source%"') do (
    set /a TCounter+=1
    set FileName=%%~nxa
    set FullPath=%%~fa
    Call :Rename
    set /a CountN+=1
    if !CountN! EQU 9 set /a CountN=0& set /a CountL+=1
    if !TCounter! EQU 234 goto :Exit
    )
    :Exit
    exit
    :Rename
    ren "!Fullpath!" "!Letters:~%CountL%,1!!Numbers:~%CountN%,1!!FileName!"
    goto :EOF
    

    This is the [a-z][a-z][1-9][1-9]filename.ext version:

    @echo off
    SetLocal EnableDelayedExpansion
    set Source=%userprofile%\desktop\Test
    set Letters=abcdefghijklmnopqrstuvwxyz
    set Numbers=123456789
    set /a CountL=0
    set /a CountN=0
    set /a CountL2=0
    set /a CountN2=0
    
    for /f "Delims=" %%a in ('dir /b /o-d /tc /s /a-d "%Source%"') do (
    
    set FileName=%%~nxa
    set FullPath=%%~fa
    Call :Rename
    set /a CountN2+=1
    if !CountN2! EQU 9 set /a CountN2=0& set /a CountN+=1
    IF !CountN! EQU 9 set /a CountN=0& set /a CountN2=0& set /a CountL2+=1
    IF !CountL2! EQU 26 set /a CountL+=1
    )
    :Exit
    exit
    :Rename
    ren "!Fullpath!" "!Letters:~%CountL%,1!!Letters:~%CountL2%,1!!Numbers:~%CountN%,1!!Numbers:~%CountN2%,1!!FileName!"
    goto :EOF