NickAtBest
NickAtBest

Reputation: 13

Split string in batch file

I am new to using batch files so could someone please help me split a string i am getting from a file.
I am using %USERPROFILE% to get my string.
The string is: "C:\Users\nicholas"
I would like to keep the C:\ part, but get rid of the \Users\nicholas part.

Upvotes: 1

Views: 892

Answers (3)

npocmaka
npocmaka

Reputation: 57252

I As you need the drive where where the users are located you can use directly %systemdrive% variable - this is the drive where the windows is installed

II the easiest way to get a drive from path:

for %%a in ("%userprofile%") do echo %%~da\

%~da - expands a path to its drive only

III over-complicated but powerful way (split function that can be used for a different things):

@echo off

call :split "%userprofile%" "\" 1 drive

echo %drive%\


goto :eof

:split [%1 - string to be splitted;%2 - split by;%3 - possition to get; %4 - if defined will store the result in variable with same name]
::http://ss64.org/viewtopic.php?id=1687

setlocal EnableDelayedExpansion

set "string=%~2%~1"
set "splitter=%~2"
set /a position=%~3

set LF=^


rem ** Two empty lines are required
echo off
for %%L in ("!LF!") DO (
    for /f "delims=" %%R in ("!splitter!") do ( 
        set "var=!string:%%~R%%~R=%%~L!"
        set "var=!var:%%~R=%%~L!"
        if "!var!" EQU "!string!" (
            echo "%~1" does not contain "!splitter!" >&2
            exit /B 1
        )
    )
)

if "!var!" equ "" (
    endlocal & if "%~4" NEQ "" ( set "%~4=")
)
if !position! LEQ 0 ( set "_skip=" ) else (set  "_skip=skip=%position%")

for /f  "eol= %_skip% delims=" %%P in (""!var!"") DO (

    if "%%~P" neq "" ( 
        set "part=%%~P" 
        goto :end_for 
    )
)
set "part="
:end_for
if not defined part (
 endlocal
 echo Index Out Of Bound >&2 
 exit /B 2
)
endlocal & if "%~4" NEQ "" (set %~4=%part%) else echo %part%
exit /b 0

Upvotes: 0

Trigger
Trigger

Reputation: 691

for /f "tokens=2 delims=\" %A in ('set userprofile') do echo %A\

See for /?

Also

echo %userprofile:~0,3%

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103467

If you carefully read the output of set /?, you'll find the answer:

May also specify substrings for an expansion.

   %PATH:~10,5%

would expand the PATH environment variable, and then use only the 5 characters that begin at the 11th (offset 10) character of the expanded result.

So, you can use something like this to get the first 3 characters of your string:

> echo %userprofile:~0,3%
C:\

Upvotes: 0

Related Questions