stringbatch-filereplacecmd

Batch file: How to replace "=" (equal signs) and a string variable?


Besides SED, how can an equal sign be replaced? And how can I use a string variable in string replacement?

Consider this example:

For /F "tokens=*" %%B IN (test.txt) DO (
   SETLOCAL ENABLEDELAYEDEXPANSION
   SET t=is
   SET old=%%B
   SET new=!old:t=!
   ECHO !new!

   ENDLOCAL
)

:: SET new=!old:==!

Two problems:

First, I cannot use the variable %t% in !:=!.

   SET t=is
   SET old=%%B
   SET new=!old:t=!

Second, I cannot replace the equal sign in the command line

   SET new=!old:==!

Solution

  • I just created a simple solution for this myself, maybe it helps someone.

    The disadvantage (or advantage, depends on what you want to do) is that multiple equal signs one after another get handled like one single equal sign. (example: "str==ing" gives the same output as "str=ing")

    @echo off
    set "x=this is=an test="
    echo x=%x%
    
    call :replaceEqualSign in x with _
    echo x=%x%
    
    pause&exit
    
    
    :replaceEqualSign in <variable> with <newString>
        setlocal enableDelayedExpansion
        
            set "_s=!%~2!#"
            set "_r="
        
            :_replaceEqualSign
                for /F "tokens=1* delims==" %%A in ("%_s%") do (
                    if not defined _r ( set "_r=%%A" ) else ( set "_r=%_r%%~4%%A" )
                    set "_s=%%B"
                )
            if defined _s goto _replaceEqualSign
        
        endlocal&set "%~2=%_r:~0,-1%"
    exit /B
    

    As you have seen, you use the function like this:

    call :replaceEqualSign in variableName with newString