3

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?

  • 1
    Are you talking about Windows batch files? – Rafael Mar 20 '15 at 15:32
  • Is it possible for you to use something with more powerful syntax, like Windows PowerShell? – amphetamachine Mar 20 '15 at 15:45
  • @Rafael yap, cmd.exe batch. sorry i didnt make that clear. –  Mar 20 '15 at 20:45
  • @amphetamachine it is, w2k8. –  Mar 20 '15 at 20:46
  • @all powershell/ bash/ perl/ etc could have been used. i was kind of curious if there's a neat solution in pure cmd.exe-batch. i feared the answer would comprise 10-20 LOC.. –  Mar 20 '15 at 20:47
  • thank you @-Aacini & @-MC ND for your implementations, i'll appreciate & memorise them nevertheless! –  Mar 20 '15 at 20:48
  • https://stackoverflow.com/questions/1103994/how-to-run-multiple-bat-files-within-a-bat-file?rq=1#comment23603317_1103994 –  Mar 20 '15 at 21:31

3 Answers3

2
@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.

MC ND
  • 69,615
  • 8
  • 84
  • 126
1

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
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • Thank you Aacini, i'll take a closer look at this later (+ see comments above..). –  Mar 20 '15 at 20:54
1

I would use my JREN.BAT regular expression rename utility - a hybrid JScript/batch script that runs natively on any Windows machine form XP onward.

jren "^([A-Z][a-z])[a-z]*(?=[A-Z])" $1 /d /t /p c:\users

The /T option is test mode, meaning it only displays the proposed rename results. Remove the /T option to actually rename the folders.

dbenham
  • 127,446
  • 28
  • 251
  • 390