Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch: how to split string on uppercase letter

I have a directory structure containing home directories named after the users full name (ForenameSurname), like:

/user/JohnDoe
/user/JaneDoe
/user/MobyDick

Now i want to copy the whole structure, changing ForenameSurname to "'first two letters of first name'+'surname'", resulting:

/user/JoDoe
/user/JaDoe
/user/MoDick

I know how to get substrings (~n), but how to split a string on the first capital letter? Is it possible at all using pure batch?


2 Answers

@echo off
    setlocal enableextensions enabledelayedexpansion

    set "root=%cd%\users"

    for /d %%f in ( "%root%\*" ) do (
        set "name=%%~nxf"
        for /f %%a in ("!name:~0,2!"
        ) do for /f "tokens=* delims=abcdefghijklmnopqrstuvwxyz" %%b in ("!name:~2!"
        ) do if not "%%~nxf"=="%%~a%%~b" if not exist "%root%\%%~a%%~b" (
            echo ren "%%~ff" "%%~a%%~b"
        ) else (
            echo "%%~nxf" can not be renamed to "%%~a%%~b"
        )
    )

Rename operations are only echoed to console. If the output is correct, remove the echo that prefixes the ren command.

like image 193
MC ND Avatar answered Nov 23 '25 09:11

MC ND


Try this:

@echo off
setlocal EnableDelayedExpansion

set "upcaseLetters=ABCDEFGHIJKLMNOPQRSTUVWXYZ"

cd \user
for /D %%a in (*) do (
   call :convert name=%%a
   echo New name: !name!
)
goto :EOF


:convert
set "var=%2"
:nextChar
   set "char=%var:~2,1%"
   if "!upcaseLetters:%char%=%char%!" equ "%upcaseLetters%" goto end
   set "var=%var:~0,2%%var:~3%"
goto nextChar
:end
set "%1=%var%"
exit /B
like image 40
Aacini Avatar answered Nov 23 '25 08:11

Aacini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!