georgiana_e
georgiana_e

Reputation: 1869

substitute a regex in a string in batch

I need to delete everything starting with a word from a string in a windows batch script. For example if I have the string:

This is my line delete from here.

I want to delete everything starting with the word delete and I need to obtain:

This is my line.

I have tryed this:

set line="This is my line delete from here"
set word="delete"
set delete="!word!*";
set line=!line:%delete%=!

It doesn't work what I have tryed, I have activated delayed expansion, and I am not sure if this: "set line=!line:%delete%=!" works. I have tryed this too "set line=!line:!delete!=!" but doesn't work either. I am new with batch scripting.

UPDATE: In a loop I can only do delayed expansion, and this code doesn't work:

@ECHO OFF

setlocal
for /F "delims= " %%A in (temp.txt) do ( 
    set "line=This is my line delete from here"
    ECHO original:%line%:
    set "word=delete"
    CALL set "delete=%%line:*%word%=%%"
    ECHO delete the "%word%%delete%" part
    CALL set "line=%%line:%word%%delete%=%%"
    ECHO final   :%line%:
)
endlocal 

Output:

original::
=%" was unexpected at this time.
delete the "" part
=%" was unexpected at this time.
final   ::

But if I remove the for from the code above, the output is:

original:This is my line delete from here:
delete the "delete from here" part
final   :This is my line :

My question is how can I do the same thing in a loop, with delayed expansion, as with normal expansion. I need in other words late expansion for both variables in the substitution expression the inner and the outer (set "delete=!line:*!word!=!", doesn't work). I can not find any documentation on that. Thanks.

Upvotes: 0

Views: 148

Answers (2)

georgiana_e
georgiana_e

Reputation: 1869

I have read this and the updated code based on Magoo's answer:

@ECHO OFF

setlocal
for /F "delims= " %%A in (temp.txt) do ( 
    set "line=This is my line delete from here"
    set "word=delete"
    echo line is: !line!
    for /f "delims=" %%a in ("!word!") do set delete=!line:*%%a=!
    echo delete is: !delete!
    for /f "delims=" %%a in ("!word!!delete!") do set line=!line:%%a=!
    echo line is: !line!
)
endlocal

Upvotes: 0

Magoo
Magoo

Reputation: 80023

@ECHO OFF
SETLOCAL
set "line=This is my line delete from here"
ECHO original:%line%:
set "word=delete"
CALL set "delete=%%line:*%word%=%%"
ECHO delete the "%word%%delete%" part
CALL set "line=%%line:%word%%delete%=%%"
ECHO final   :%line%:

GOTO :EOF

This should show you the steps.

First, delete the part up to and including the word. Then delete the word and the rest-of-line (in delete)

Note the placement of the quotes - to control the set not the value assigned.

Upvotes: 1

Related Questions