Search code examples
windowsbatch-filecmdrename

.bat file renaming folders, changing first letter of every word to uppercase


From C:\x\adrenaline_-_shut_the_fug_up_and_dance-2000

to C:\x\Adrenaline_-_Shut_The_Fug_Up_And_Dance-2000

I had this code but it capitalize every single letter instead

@echo off
setlocal disableDelayedExpansion
echo Renaming folders
for /d %%F in (C:\x\*) do (
  for /f "eol= " %%A in ("%%~nxF") do (
    set "name=%%F"
    set "newName=%%A"
    setlocal enableDelayedExpansion
    for %%C in (
        A B C D E F G H I J K L M
        N O P Q R S T U V W X Y Z
    ) do set "newName=!newName:%%C=%%C!"
    ren "!name!" "!newName!"
    endlocal
  )
)

thank you!


Solution

  • How about this modification? I think that this might be able to write more simpler. So please think of this as one of several answers.

    Modification points :

    • Retrieve the initial letter from filename, and convert it to uppercase.
    • For each initial letter in the filename, retrieve the letter using _. And the letter of behind _ is converted to uppercase.
    • Add the converted letter to the filename which was removed the initial letter.
    • If there is the same filename, it is not renamed.

    The modified script which reflected above points is as follows.

    Modified script :

    @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    ECHO Renaming folders
    
    SET "DIR=C:\x\"
    
    FOR /D %%F IN (%DIR%*) DO (
      SET "BASENAME=%%~NXF"
      SET "NAME=%%~NXF"
      SET "F=TRUE"
      SET "NEWNAME="
      CALL :CONVERT
    )
    EXIT /B
    
    :CONVERT
    SET "L=!NAME:~0,1!"
    IF %F% == TRUE (
      SET "INITIAL=!L!"
      FOR %%I IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET INITIAL=!INITIAL:%%I=%%I!
      SET NEWNAME=!NEWNAME!!INITIAL!
    ) ELSE (
      SET NEWNAME=!NEWNAME!!L!
    )
    IF !L! == _ (
      SET "F=TRUE"
    ) ELSE (
      SET "F=FALSE"
    )
    SET "NAME=!NAME:~1!"
    IF DEFINED NAME GOTO CONVERT
    IF NOT %DIR%!BASENAME! == %DIR%!NEWNAME! REN "%DIR%!BASENAME!" "!NEWNAME!"
    EXIT /B
    

    Note :

    • When you use this, please modify SET "DIR=C:\x\" for your environment.
    • Please be careful _ of the filename, because the letters for converting to the uppercase are retrieved using _.

    If I misunderstand your question, I'm sorry.