ilias
ilias

Reputation: 334

Remove substring from a string

How to remove a substring passed by variable, from a string, within for and other loops (delayedExpansion required) ?

i found a %% :

@echo off
setlocal enableExtensions enableDelayedExpansion
cd /D "%~dp0"
set br=^


rem br;


set "v=1!br!2!br!3"
set v=%%v:%br%=%%
echo !v!

but it doesn't seem to work, and it won't work if the v variable going to change between iterations (when %..% need to be !..!).

Any help is appreciated.

Upvotes: 0

Views: 337

Answers (3)

Compo
Compo

Reputation: 38623

Here's an additional example with some Remarks:

@Echo Off
Rem Using delayed expansion is necessary for this task.
SetLocal EnableDelayedExpansion
Rem The two empty lines are necessary to set br to a new line.
Set br=^


Rem Use the variable named br to set a variable named v to a multiline value.
Set "v=1!br!2!br!3"
Rem You can output all variable names beginning with v with their values using the below command.
Set v
Rem You can output the value for the variable named v using the below command.
Echo !v!
Pause

If you cannot guarantee that the variable named v will have a value:

  • In order to prevent the fourth last line outputting Environment variable v not defined, you should use Set v 2>Nul instead.

  • In order to prevent the second last line outputting ECHO is off., you should use Echo(!v! instead.

To remove all instances of the string value of !br! from the now existng variable named v, you would need to use a Call statement to introduce another parsing level:

Rem Expand the variable named v and substitute the string value of the variable named br with nothing.
Call Set "v=%%v:!br!=%%"
Rem You can output the new value for the variable named v using the below command.
Echo(!v!
Rem However as Delayed Expansion is no longer necessary, you could instead use.
Echo(%v%

Upvotes: 0

user7818749
user7818749

Reputation:

You could alternatively use echo| set /p = in a for loop.

@echo off
setlocal enableDelayedExpansion
cd /D "%~dp0"
set br=^


:# Above 2 lines must be empty.
set "v=1!br!2!br!3"
for %%i in (!v!) do echo| set /p =%%i

Upvotes: 0

Stephan
Stephan

Reputation: 56180

You found a %%, but obviously you found not all neccessary information. First, br has to be used as !br!. %br% doesn't work. Second, the %%var%% notation is to be used with call (forcing a second layer of parsing):

@echo off
setlocal enableExtensions enableDelayedExpansion
cd /D "%~dp0"
set br=^


rem br;

set "v=1!br!2!br!3"
call set "v=%%v:!br!=%%"
echo !v! (also: %v%)

Upvotes: 1

Related Questions