Batch file 在批处理文件中拆分字符串

Batch file 在批处理文件中拆分字符串,batch-file,Batch File,我不熟悉使用批处理文件,请有人帮我拆分文件中的字符串。 我正在使用%USERPROFILE%获取我的字符串。 字符串是:“C:\Users\nicholas” 我想保留C:\part,但要去掉\Users\nicholas部分。如果仔细阅读set/?的输出,您会找到答案: 也可以为展开指定子字符串 %PATH:~10,5% 将展开PATH环境变量,然后仅使用5 以展开字符的第11个(偏移量10)字符开始的字符 结果 因此,您可以使用类似的方法获取字符串的前3个字符: > echo

我不熟悉使用批处理文件,请有人帮我拆分文件中的字符串。
我正在使用
%USERPROFILE%
获取我的字符串。
字符串是:
“C:\Users\nicholas”


我想保留
C:\part
,但要去掉
\Users\nicholas
部分。

如果仔细阅读
set/?
的输出,您会找到答案:

也可以为展开指定子字符串

   %PATH:~10,5%
将展开PATH环境变量,然后仅使用5 以展开字符的第11个(偏移量10)字符开始的字符 结果

因此,您可以使用类似的方法获取字符串的前3个字符:

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


I由于需要用户所在的驱动器,您可以直接使用
%systemdrive%
变量-这是安装windows的驱动器

II从路径获得驾驶权的最简单方法:

for %%a in ("%userprofile%") do echo %%~da\
%~da
-仅扩展到其驱动器的路径

III过于复杂但功能强大的方式(可用于不同事物的拆分功能):

你可以在这里找到答案:
echo %userprofile:~0,3%
for %%a in ("%userprofile%") do echo %%~da\
@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