将带有符号的变量分成不同的部分

use*_*296 7 string batch-file

使用批处理,我希望能够将一个变量分成两个或三个部分,当有一个符号除以它们.例如,如果我有这样的字符串:var1; var2;

我如何让var1变为变量,var2变为另一个变量.

提前致谢

roj*_*ojo 11

将变量拆分为数组(或者像Windows批处理可以模仿的那样接近数组)的最佳方法是将变量的值放入for循环可以理解的格式中. for没有任何开关将逐字分割,在csv类型分隔符(逗号,空格,制表符或分号)分割.

这比for /f逐行循环而不是逐字循环更合适,并且它允许分割未知数量的元素的字符串.

这里基本上是如何与for循环分裂.

setlocal enabledelayedexpansion
set idx=0
for %%I in ("%var:;=","%") do (
    set "var[!idx!]=%%~I"
    set /a "idx+=1"
)
Run Code Online (Sandbox Code Playgroud)

重要的部分是用引号代;","in %var%,并用引号将整个事物括起来.实际上,这是分割环境变量的最优雅的方法%PATH%.

这是一个更完整的演示,调用子程序来分割变量.

@echo off
setlocal enabledelayedexpansion

set string=one;two;three;four;five;

:: Uncomment this line to split %PATH%
:: set string=%PATH%

call :split "%string%" ";" array

:: Loop through the resulting array
for /L %%I in (0, 1, %array.ubound%) do (
    echo array[%%I] = !array[%%I]!
)

:: end main script
goto :EOF


:: split subroutine
:split <string_to_split> <split_delimiter> <array_to_populate>
:: populates <array_to_populate>
:: creates arrayname.length (number of elements in array)
:: creates arrayname.ubound (upper index of array)

set "_data=%~1"

:: replace delimiter with " " and enclose in quotes
set _data="!_data:%~2=" "!"

:: remove empty "" (comment this out if you need to keep empty elements)
set "_data=%_data:""=%"

:: initialize array.length=0, array.ubound=-1
set /a "%~3.length=0, %~3.ubound=-1"

for %%I in (%_data%) do (
    set "%~3[!%~3.length!]=%%~I"
    set /a "%~3.length+=1, %~3.ubound+=1"
)
goto :EOF
Run Code Online (Sandbox Code Playgroud)

这是上面脚本的输出:

C:\Users\me\Desktop>test.bat
array[0] = one
array[1] = two
array[2] = three
array[3] = four
array[4] = five
Run Code Online (Sandbox Code Playgroud)

只是为了好玩,尝试取消评论该set string=%PATH%行,让好时光滚动.


End*_*oro 9

Tokens=1,2确实创建了两个for循环变量%%i%%j&分裂string两部分,用分隔符分隔;:

@echo off &setlocal
set "string=var1;var2;"
for /f "tokens=1,2 delims=;" %%i in ("%string%") do set "variable1=%%i" &set "variable2=%%j"
echo variable1: %variable1%
echo variable2: %variable2%
endlocal
pause
Run Code Online (Sandbox Code Playgroud)

对于更"动态"的方法,请使用:

@echo off &setlocal enabledelayedexpansion
set "string=var1;var2;"

set /a count=0
for %%i in (%string%) do (
    set /a count+=1
    set "variable!count!=%%i"
)
echo found %count% variables
for /l %%i in (1,1,%count%) do (
    echo variable%%i: !variable%%i!
)
endlocal
Run Code Online (Sandbox Code Playgroud)