user2907999
user2907999

Reputation: 185

removing characters till a specific substring

I have a string like ' ntuser.dat ntuser.dat.log ntuser.ini test.bat test1.bat advice.20131024.98767 textdoc.txt'
I would like to remove all characters from the specified string till 'advice.20131024'
How can i do this using windows batch commands?
I also need to save the result string in a variable
thanks in advance

Upvotes: 1

Views: 2558

Answers (2)

foxidrive
foxidrive

Reputation: 41234

This sets the string,
changes it to delete everything up until the end of advice and replace it with advice
then echoes the rest of the string.

set "string=ntuser.dat ntuser.dat.log ntuser.ini test.bat test1.bat advice.20131024.98767 textdoc.txt"
set "string=%string:*advice=advice%"
echo "%string%"

Upvotes: 5

MC ND
MC ND

Reputation: 70923

(a) Searching in string

    set text=ntuser.dat ntuser.dat.log ntuser.ini test.bat test1.bat advice.20131024.98767 textdoc.txt

:loop
    if "%text:~0,6%"=="advice" goto exitLoop
    set text=%text:~1%
    goto loop

:exitLoop
    echo %text%

(b) with for loop

@echo off
    setlocal enableextensions enabledelayedexpansion

    set text=ntuser.dat ntuser.dat.log ntuser.ini test.bat test1.bat advice.20131024.98767 textdoc.txt
    set result=

    for %%f in (%text%) do (
        set x=%%f
        if "!x:~0,6!"=="advice" (
            set result=%%f
        ) else (
            if not "!result!"=="" set result=!result! %%f
        )
    )

    echo %result%

(c) See foxidrive answer (i always forget that)

Upvotes: 1

Related Questions