rename files in folder batch utility code example

Example 1: batch rename folders

REM # (1) Rename folders (not files) in the current folder only
REM # (2) Rename folders (not files) in the current folder and its subfolders

REM # | EXAMPLE (1) 
REM # | ---------------------------------------------------------------
REM # | Replace " " with "_" for the folders in the current folder only    

@echo off
setlocal EnableDelayedExpansion
set "pattern_to_replace= "
set "replace_text=_"

for /d %%N in ("*") do (
   set "InitName=%%N"
   call set NewName=%%InitName:!pattern_to_replace!=!replace_text!%%
   
   if NOT !InitName!==!NewName! (
      echo rename "!InitName!" "!NewName!" 
      rename "!InitName!" "!NewName!"
   )
)

@echo on


REM # | EXAMPLE (2) 
REM # | ---------------------------------------------------------------
REM # | Replace " " with "_" for the folders in the current folder and all its subfolders

@echo off
setlocal EnableDelayedExpansion
set "pattern_to_replace= "
set "replace_text=_"

for /d /R "%cd%" %%N in ("*") do (
   set "InitName=%%~nN%%~xN"
   call set NewName=%%InitName:!pattern_to_replace!=!replace_text!%%

   if NOT %%N==%%~dN%%~pN!NewName! (
      echo rename "%%~dN%%~pN!InitName!" "!NewName!" 
      rename "%%~dN%%~pN!InitName!" "!NewName!"
   )
)

@echo on

REM # | ---------------------------------------------------------------

Example 2: batch rename files

REM # (1) Rename files (not folders) in the current folder only
REM # (2) Rename files (not folders) in the current folder and its subfolders

REM # | EXAMPLE (1) 
REM # | ---------------------------------------------------------------
REM # | Replace ")" with "_" within the filenames in the current folder only    

@echo off
setlocal EnableDelayedExpansion
set "pattern_to_replace=("
set "replace_text=_"

for %%N in ("*") do (
   set "InitName=%%N"
   call set NewName=%%InitName:!pattern_to_replace!=!replace_text!%%

   if NOT !InitName!==!NewName! (
      echo rename "!InitName!" "!NewName!" 
      rename "!InitName!" "!NewName!"
   )
)

@echo on


REM # | EXAMPLE (2) 
REM # | ---------------------------------------------------------------
REM # | Replace ")" with "_" within the filenames in the current folder and all its subfolders

@echo off
setlocal EnableDelayedExpansion
set "pattern_to_replace= "
set "replace_text=_"

for /R "%cd%" %%N in ("*") do (
   set "InitName=%%~nN%%~xN"
   call set NewName=%%InitName:!pattern_to_replace!=!replace_text!%%

   if NOT %%N==%%~dN%%~pN!NewName! (
      echo rename "%%~dN%%~pN!InitName!" "!NewName!"
      rename "%%~dN%%~pN!InitName!" "!NewName!"
   )
)

@echo on

REM # | ---------------------------------------------------------------