Batch - Rename subfolder

Viewed 84

I'm trying to create a Batch to rename all the subfolders that have "_" in the name. This works but only for folders under the TEST path.

How can I go to subfolders too?

Example C:\TEST\name_TMP the result is C:\TEST\name

Instead with C:\TEST\name\name_TMP the script doesn't work

@echo off
setlocal EnableDelayedExpansion
set "SourceDir=C:\TEST\"
FOR /d %%i IN ("%SourceDir%\*") DO (
   set "FolderName=%%~nxi"
   if "!FolderName:~-4,1!"=="_" REN "%%~i" "!FolderName:~0,-4!"
)
endlocal

Maybe, if possible, find and remove only the _TMP part

2 Answers

This is your code with slight adjustments:

@echo off
setlocal EnableDelayedExpansion
set "SourceDir=C:\TEST"
FOR /F "delims=" %%i IN ('dir /b /s /a:d "%SourceDir%\*" ^| findstr /R "_TMP$"') DO (
   set "Folder=%%~fi"
   echo ren "%%~fi" "!Folder:_TMP=!"
)

Only remove echo once you confirmed the output is what you expect it to be. Note, this is untested as I posted from my mobile.

This one works

cd /d e:\ && FOR /F "tokens=1* delims=_" %a in ('dir /ad /on /b /s *_TMP* |find /i "_TMP" |sort /r') do ren "%a_%b" "%~nxa"
Related