Анна Кен
Анна Кен

Reputation: 21

How to split String with cmd bat using delimiter as entire word

How to split string with the delim=string E.g:

split string

"sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz"

by

delim="MYSTR" 

and result should be:

sssssMssss
___M___
zzzzzzMzzzz

Such code

for /f "tokens=1,2 delims=MYSTR" %%A in ("sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz") do (
         set fn1=%%A
     )

doesn't work/ It splits only using first letter by 'M'

How to split by word?

Upvotes: 2

Views: 9367

Answers (2)

Aacini
Aacini

Reputation: 67216

@echo off
setlocal EnableDelayedExpansion

set "string=sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz"

rem Do the split:
set i=1
set "fn!i!=%string:MYSTR=" & set /A i+=1 & set "fn!i!=%"

set fn

Output:

fn1=sssssMssss
fn2=___M___
fn3=zzzzzzMzzzz

You may review this topic for a detailed explanation on the method used...

Upvotes: 2

npocmaka
npocmaka

Reputation: 57252

try with split.bat (you can use both as a function or a separate bat file (does not handle well !,% and ")) :

@echo off
setlocal
call :split "sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz" MYSTR 1 spl1
echo %spl1%
call :split "sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz" MYSTR 2 spl2
echo %spl2%
call :split "sssssMssssMYSTR___M___MYSTRzzzzzzMzzzz" MYSTR 3
rem echo %spl2%

endlocal & exit /b %errorlevel%


: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: 1

Related Questions