Search code examples
windowsbatch-filefile-renamebatch-rename

Rename large amount of files using a counter loop within subfolders with a batch file - Windows 7


In Windows 7, I have a folder which only contains subfolders and no files. Within the subfolders, I have a bunch of .dcm files (medical images). The files within each subfolder have the same name, and I want them to all have different names, more specifically, I want the names to be order 1.dcm, 2.dcm, 3.dcm, etc.

Current situation: Folders A, B, and C, and each folder contains File1.dcm, File2.dec, File3.dcm Would like to have this: Folder A contains files 1.dcm, 2.dcm, 3.dcm Folder B contains files 4.dcm, 5.dcm, 6.dcm Folder C contains files 7.dcm, 8.dcm, 9.dcm

Is there a way to write a batch file that goes into each subfolder in order and renames the files in numerical order? I am very much the novice when it comes to writing script for Windows and have no idea how to go about doing this. I found code that changes file extensions within subfolders, but nothing that does what I am looking for.

Any help is greatly appreciated!


Solution

  • @Echo off
    For /f "tokens=1* delims=:" %%A in (
      'Dir /B/S/ON/A-D "X:\path\to\folder\*.dcm" ^|findstr /N /V "^$"'
    ) Do Echo Ren "%%~fB" "%%A%%~xB"
    

    If the output seems ok remove the echo in the last line.
    If you have numbers with different length in one folder be aware that sorting by name will have 10 before 2.


    For better understanding some explanations:

    Dir /B/S/ON/A-D "X:\path\to\folder*.dcm"
    /Bare format
    /Subdtree recurse
    /Order by Name
    /Attribute -(not) Directory

    Findstr /N /V "^$"
    /Number each output line delimit with a colon.
    /inVerse the match
    "^$" a Regular Expression meaning an empty line
    ^ matches the begin of a line
    $ matches the end of a line

    For /f "tokens=1* delims=:" %%A in ('command') do
    Parses output of 'comand' into tokens 1=%%A and *=rest into %%B
    the delimiter : is only used for token 1,
    token 2 takes the rest of the line (important to preserve the drive colon)

    The vars %%A and %%B are passed to the do (part)

    The for vars can be modfied with ~ modifiers see For /?
    %%~fB ~f meaning fullname including dirve and path,
    %%A%%~xB ~x is the extension from %%~xB including the dot