Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

i have one big folder with many folders with some files, like this:

img 08-21
- japan.jpg; 
- german.jpg;
- london.jpg;

img 08-22
- caribic.jpg
- malta.jpg

ims 08-23
- center.jpg
- circle.jpg
- bike.jpg

and i want to rename by batch(.bat or whatever for winXP cmd) to

01-img 08-21
- 01-japan.jpg
- 01-german.jpg
- 01-london.jpg

02-img 08-22
- 02-caribic.jpg
- 02-malta.jpg

03-ims 08-23
- 03-center.jpg
- 03-circle.jpg
- 03-bike.jpg

I want to rename folder to prefix(number)-folder and files (in folder) to prefix(folder)-file. Can somebody pls help me?

share|improve this question

The following batch file should solve this. Explanations follow below.

@echo off
setlocal enableextensions enabledelayedexpansion
set counter=0
for /d %%d in (*) do (
    set /a counter+=1
    call :lz
    pushd %%d
    for %%f in (*) do ren "%%f" "!counter!-%%f"
    ren "%%d" "!counter!-%%d"
goto :eof
set counter=000%counter%
rem adapt this to allow for three-digit numbering
set counter=%counter:~-2%
goto :eof

Basically this loops over all directories with

for /d %%d in (*)

The /d switch here is for looping only over directories. The current directory within the loop is stored in %%d. Then the counter (which is set to 0 at the start) is incremented by one and padded appropriately at the start with zeroes if necessary. This is done by the call to the :lz subroutine. Within that subroutine (it's at the end of the batch) the number of digits can be changed in the line

set counter=%counter:~-2%

by changing the 2 to 3 or so.

Then the directory will be changed to the one we're currently handling using pushd (which has the nice property that we can undo this directory change afterwards by using popd) and another loop is performed, this time over the files inside the directory:

for %%f in (*) do ren "%%f" "!counter!-%%f"

which renames the files and prepends the counter value to them. The exclamation marks around the counter variable name are so-called delayed expansion which is necessary here (why this is so can be read up in help set).

After renaming all files in the directory we jump out of it again and rename the directory itself. Nothing too fancy here.

share|improve this answer
Nice answer. Good explanations too! – RJFalconer Jan 2 '10 at 17:47

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.