Separation of a variable with a symbol into different parts

using a batch, I want to be able to split a variable into two or three parts when there is a symbol dividing them. for example, if I have a line that looks like this: var1; var2;

how can i get var1 to become a variable and var2 to become different.

Thanks at Advance

+5
source share
2 answers

Tokens=1,2creates two variables for the loop %%iand %%j& splits stringinto two parts separated by a separator ;:

@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

For a more "dynamic" method, use this:

@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
+7
source

( , 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"
)

; "," %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

script:

C:\Users\me\Desktop>test.bat
array[0] = one
array[1] = two
array[2] = three
array[3] = four
array[4] = five

set string=%PATH% .

+10

All Articles