0

I have some very complex variables and am trying to replace part of the long variable with a different variable.

SETLOCAL EnableDelayedExpansion

SET var1=Name=@something,also.something;else
SET var2=REPLACEMENT
SET var3="v2.30|Action-Maybe|Active=Possible|Name=@something,also.something;else|Microsoft.windows.programs://Microsoft.com|"


call set var3=%%var3:!var1!=!var2!%%

ECHO %var3%

However, when I do so, I get the following Output:

"v2.30|Action-Maybe|Active=Possible|@something,also.something;else=REPLACEMENT=@something,also.something;else|Microsoft.windows.programs://Microsoft.com|"

Note how Name= has disappeared from the beginning of the part of text I'm trying to replace.

Also note how the replacement variable is appearing twice (both times missing Name=).

I know the problem probably lies in the line:

call set var3=%%var3:!var1!=!var2!%%

But I'm unsure how to escape the '=' character contained in the replacement variable... Assuming that's what causing the problem, of course...

Arianax
  • 9
  • 4
  • In my opinion, the issue is that you're using the wrong tool for the job. Batch files were not designed for this type of task. On most Windows systems Windows Scripting Host, _(`VBScript` and `JScript`)_, and `PowerShell` are available and much better suited. – Compo Apr 01 '20 at 13:37
  • Well, the core problem is that the first equal-to sign in the sub-string substitution syntax separates search from replace strings, so after delayed expansion the remainder is `set var3=%var3:Name=@something,also.something;else=REPLACEMENT%`, which defines `Name` as the search string and everything behind the next `=` as the replace string; and there is unfortunately no method of escaping... – aschipfl Apr 07 '20 at 23:33

1 Answers1

0

using substring modification on a variable or string containing = will not work as intended.

It is a much simpler process to just replace the component of the variable to be modified by redefining it with the aid of a subroutine. This subroutine is designed to be safe for use with a wide range of characters.

@Echo Off
Goto :main

:Sub
    PUSHD "%~dp0"
    Setlocal DisableDelayedExpansion
    Echo("%~2">SubVar.tmp
    For /F "Tokens=* Delims=" %%A in (SubVar.tmp) Do Set ^"Substring=%%~A"

POPD
(
Endlocal & Set %~1="v2.30|Action-Maybe|Active=Possible|%Substring%|Microsoft.windows.programs://Microsoft.com|"
Exit /B
)

:main
    Call :Sub Var3 "REPLACEMENT"
    Echo(%Var3%

    Call :Sub Var3 "New REPLACEMENT <> & ! ` ! ~ |"
    Echo(%Var3%
T3RR0R
  • 2,747
  • 3
  • 10
  • 25
  • If you need to modify different sections of the variable you are working with frequently, you can adapt this by splitting the string into the core components as variables (4 core components = 4 variables), and using additional parameters in the subroutine and call to bookend the sub string with the relevent components. – T3RR0R Apr 01 '20 at 14:58