Command Prompt/Batch - rename multiple files with sequential numbering

user3108268 picture user3108268 · Mar 17, 2017 · Viewed 11.7k times · Source

Lets say I have multiple files

filename.a.txt
filename.b.txt
filename.c.txt

I want to run a batch file that targets all .txt files and rename them to whatever I have set into my custom %filename% var + give them numbers so it would end up into something like:

filename.1.txt
filename.2.txt
filename.3.txt

So far I have wrote this:

set filename=FileTitle
for /r %%i in (*.txt) do call ren %%i %filename%.txt

And it works, but problem is that it just picks up first .txt file and gives it the FileTitle filename and that's it. I can't figure how to rename all .txt files in a batch and give them unique sequential number as a prefix/suffix/custom var to the outputed %filename%.txt so something like e.g. %filename%-%uniquesuffix%.txt. So I need to set some kind of variable that gives each file a unique number e.g. from 1-99 in alphabet order (default order that cmd prompt picked files up).

I did search other answers, but they show only how to add global/same prefix to renamed files.

Answer

Aacini picture Aacini · Mar 17, 2017
@echo off
setlocal EnableDelayedExpansion

set filename=FileTitle
set suffix=100
for /F "delims=" %%i in ('dir /B *.txt') do (
   set /A suffix+=1
   ren "%%i" "%filename%-!suffix:~1!.txt"
)

This code renames the files in the form you requested. Note that the numeric suffix have two digits in order to preserve the original alphabet order of the files. If "natural" 1-99 numbers were used, then the order in that cmd prompt show the files is changed in this way: 1.txt 10.txt 11.txt ... 19.txt 2.txt 20.txt 21.txt ... 29.txt 3.txt ... (alphabet order, NOT numeric one). If may be more than 99 files, just add another zero in set suffix=100 command to generate a three-digits suffix.

Note also that your plain for command may process some files twice or more times depending on the site where the renamed files will be placed in the original files list. To avoid this problem use a for /F command over a dir /B *.txt one. This method first get a list of all files, and then execute the renames over such a static list.

To process all files under current folder (that is the purpose of your /r switch in for command), just add a /S switch in the dir command.