Page 1 of 1

Delete substring using variable inside for /f

Posted: 20 Dec 2018 10:26
by Blazer
I am trying to delete a substring from a variable using another variable inside a for /f loop.

The "Setlocal EnableDelayedExpansion" is required for other code.

The following example does not work.

Please help.

Thank you.

Code: Select all

@Echo off

for /f "delims=" %%F in ('dir /b "C:\Windows"') do (

Setlocal EnableDelayedExpansion

Set _cities="Aberdeen, London, Edinburgh"

Set _substr=Rome

Set _dummy=!_cities:!_substr!=!

Echo !_dummy!

If Not "!_dummy!"=="!_cities!" (Echo !_substr! was found.) Else (Echo !_substr! was not found.)

Endlocal

)

Re: Delete substring using variable inside for /f

Posted: 20 Dec 2018 15:41
by aGerman
Probably:

Code: Select all

Set _dummy=!_cities:%_substr%=!
Steffen

Re: Delete substring using variable inside for /f

Posted: 21 Dec 2018 03:22
by Blazer
Thank you for your input Steffen, unfortunately that does not work :(

Here is the new code:

Code: Select all

@Echo off

for /f "delims=" %%F in ('dir /b "C:\Windows"') do (

Setlocal EnableDelayedExpansion

Set _cities="Aberdeen, London, Edinburgh"

Set _substr=Rome

Set _dummy=!_cities:%_substr%=!

Echo !_dummy!

If Not "!_dummy!"=="!_cities!" (Echo !_substr! was found.) Else (Echo !_substr! was not found.)

Endlocal

)

Re: Delete substring using variable inside for /f

Posted: 21 Dec 2018 07:31
by aGerman
Is it mandatory that you set the value of _substr inside of the parenthesized block? If not, just set the value before you run the loop. Otherwise it will get more tricky:

Code: Select all

for /f "delims=" %%S in ("!_substr!") do Set _dummy=!_cities:%%S=!
Steffen

Re: Delete substring using variable inside for /f

Posted: 23 Dec 2018 05:28
by Blazer
That does work but I was hoping to find a way to fix the existing code without adding another for loop.

Maybe some extra exclamation or percent characters.

Thanks.

Re: Delete substring using variable inside for /f

Posted: 24 Dec 2018 00:11
by Squashman
Call Set "_dummy=%%_cities:!_substr!=%%"

Re: Delete substring using variable inside for /f

Posted: 25 Dec 2018 06:20
by Blazer
@aGerman
@Squashman

Thank you for your help :D

Re: Delete substring using variable inside for /f

Posted: 02 Jan 2019 05:22
by Blazer
This problem has been solved by both @aGerman and @Squashman :)

But I wonder if its possible to tweak the solution from @Squashman so that it works without the call statement?

Call Set "_dummy=%%_cities:!_substr!=%%"

Thank you