2

I have read this post and I can't meet my requirements.

My Folder structure is:

_TEMPLATE_
|_ _TEMPLATE_SUBFOLDER1
|   |_ _TEMPLATE_SUB_SUBFOLDER1
|   |   |_ _TEMPLATE_FILE11.txt
|   |   |_ _TEMPLATE_FILE12.xml
|   |_ _TEMPLATE_SUB_SUBFOLDER2
|   |   |_ _TEMPLATE_FILE21.txt
|   |   |_ _TEMPLATE_FILE22.xml
|   |_ TEMPLATE_SUB_SUBFOLDER3
|_ _TEMPLATE_SUBFOLDER2
    |_TEMPLATE_FILE3.xml

I want to replace the _TEMPLATE_ to desired name for ex. Stores so result will be

Stores
|_ StoresSUBFOLDER1
|   |_ StoresSUB_SUBFOLDER1
|   |   |_ StoresFILE11.txt
|   |   |_ StoresFILE12.xml
|   |_ StoresSUB_SUBFOLDER2
|   |   |_ StoresFILE21.txt
|   |   |_ StoresFILE22.xml
|   |_ StoresSUB_SUBFOLDER3
|_ StoresSUBFOLDER2
    |StoresFILE3.xml

I searched web there is option to traverse only files. and none of them go recursive rename Thank you.

Community
  • 1
  • 1
Mahendran
  • 2,719
  • 5
  • 28
  • 50
  • 1
    possibe duplicate: http://stackoverflow.com/questions/717171/recursive-renaming-file-names-folder-names-with-a-batch-file – Dirk Mar 06 '12 at 12:27
  • @Dirk thanks.. :) the post help me on renaming files but it didn't renaming folders.. anyway half of the work done.. how to recursively rename subfolders? – Mahendran Mar 06 '12 at 13:00
  • To rename folders you'll have to use an additional loop, but with `for /r /d`. – MBu Mar 06 '12 at 14:44

1 Answers1

4

Untested, but I think this will work

@echo off
setlocal disableDelayedExpansion
for /f "delims=" %%F in ('dir /b /ad /s _TEMPLATE_*') do (
  set "fname=%%~nxF"
  set "fpath=%%~dpF"
  setlocal enableDelayedExpansion
  ren "!fpath:_TEMPLATE_=Stores!!fname!" "!fname:_TEMPLATE_=Stores!"
  endlocal
)

It is perhaps a bit tricky because the loop is modifying the folder names of the hierarchy that it is enumerating. The parent folder of each folder will already have been renamed by the time it gets there.

It will not give the correct results if your root path that is not getting renamed also has _TEMPLATE_ in the name.

I toggle delayed expansion within the loop to protect against corruption of ! in path names during expansion of the FOR variable. If you know that no folder names contain ! then you can use SETLOCAL EnableDelayedExpansion at the top and remove the SETLOCAL and ENDLOCAL from the loop.

dbenham
  • 127,446
  • 28
  • 251
  • 390