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

前端 未结 6 1813
孤独总比滥情好
孤独总比滥情好 2020-12-10 07:39

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=*\"         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 08:01

    My answer from another post, but it applies here, too:

    There is an alternative that is easier. Instead of passing in a value that contains an equals sign, try something like a colon instead. Then, through the ability to modify that value (the colon), you can convert it back into an equals. Here is an example:

    @echo off
    set VALUE1=%1
    set VALUE2=%VALUE1::==%
    echo value1 = %VALUE1%
    echo value2 = %VALUE2%
    

    When you run the batch file, call it like this:

    C:\>myBatch name:someValue
    

    The output would be:

    value1 = name:someValue
    value2 = name=someValue
    

    If the name or value contains a space, you will have other issues to address, though. You will need to wrap the entire string in double quotes. But, then you have the issue of needing to get rid of them. This can also be handled, like this:

    @echo off
    cls
    set PARAM=%1
    set BASE=%PARAM:"=%
    set PAIR=%BASE::==%
    
    rem Either of these two lines will do the same thing - just notice the 'delims'
    rem for /f "tokens=1,2 delims=:" %%a in ("%BASE%") do set NAME=%%a & set VALUE=%%b
    rem for /f "tokens=1,2 delims==" %%a in ("%PAIR%") do set NAME=%%a & set VALUE=%%b
    
    for /f "tokens=1,2 delims=:" %%a in ("%BASE%") do set NAME=%%a & set VALUE=%%b
    
    echo param = %PARAM%
    echo base  = %BASE%
    echo pair  = %PAIR%
    echo name  = %NAME%
    echo value = %VALUE%
    

    When running this batch file like this:

    C:\>myBatch "some name:another value"
    

    The output will be:

    param = "some name:another value"
    base  = some name:another value
    pair  = some name=another value
    name  = some name
    value = another value
    

    Hope that helps others in their quest to win the fight with batch files.

    Mike V.

提交回复
热议问题