Search code examples
batch-filebatch-rename

Remove part of a string in a Batch (.bat) file


I need to remove part of a string so I can use the message. Tried many different ways unsuccessfully. Thanks in advance

Immagine that I have a message like this one:

SET MESSAGE="The key sequence '1' in 'http://www.myschema.com/dummy:dummy_PK' Keyref fails to refer to some key."

I need to remove this:

in 'http://www.myschema.com/dummy:dummy_PK' Keyref

And get something like this:

"The key sequence '1' fails to refer to some key."

Do note that the text between "in" and "Keyref" is variable, meaning I have to find a way to remove the text between these 2 strings (inclusively).


Solution

  • Assuming in and Keyref only appear once, and | never appears, then:

    @echo off
    setlocal enableDelayedExpansion
    set message="The key sequence '1' in 'http://www.myschema.com/dummy:dummy_PK' Keyref fails to refer to some key."
    set "message=!message: in =|!"
    set "message=!message: Keyref =|!"
    for /f "delims=| tokens=1,3" %%A in ("!message!") do set "message=%%A %%B"
    set message