Search code examples
batch-filecmdcommandcommand-prompt

Rename multiple files with a sequence of numbers in cmd and batch


This is my first question in this beautiful website. As you probably read in the title I would like to rename a variable number of files, with a sequence of numbers in cmd and a batch file, the sequence is increasing and it is like this (1, 2, 3, 4, 5, 6, 7, 8, 9, 10...). For example:

Test.txt it should become 1.txt

Another.txt should become 2.txt

And so on, all automatically.

My idea was to set up a variable like set /a number=1 and add +1 like this set number="%number%+1" to it through a loop and rename each time, but it isn't possible since when I rename files with ren command it renames all at once.

Can anyone help me providing a cmd and a batch file version?

Thanks in advance


Solution

  • This should work for you.

    set /a Index=1
    
    setlocal enabledelayedexpansion
    
    for /r %%i in (*.txt) do ( 
        rename "%%i" "!Index!.txt"
        set /a Index+=1
    )
    

    Create a batch file with above code and run it in folder where your .txt files are available.

    If you want to append "0" to make it 2 digits. you can try adding if else statement as below.

    set /a Index=1
    
    setlocal enabledelayedexpansion
    
    for /r %%i in (*.txt) do ( 
        rem if number is less than 10, append 9 to file name
        if !Index! lss 10 (
            rename "%%i" 0"!Index!.txt"
        ) else (
            rename "%%i" "!Index!.txt"
        )
        
        set /a Index+=1
    )