Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:==!
like image 909
Tin Amaranth Avatar asked Mar 04 '12 16:03

Tin Amaranth


People also ask

What is == in batch?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.


2 Answers

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
like image 183
timlg07 Avatar answered Oct 26 '22 11:10

timlg07


The setlocal enableDelayedExpansion should be moved after your old=%%B assignment in case %%B contains !.

The "t" problem is easy to solve within a loop by using another FOR variable

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

There is no simple native batch solution for replacing =. You can iterate through the string, character by character, but that is slow. Your best bet is probably to switch to VBScript or JScript, or use a non-native utility.

If you really want to do this using pure Windows batch commands, there are a couple of interesting ideas at http://www.dostips.com/forum/viewtopic.php?t=1485

like image 30
dbenham Avatar answered Oct 26 '22 11:10

dbenham