Search code examples
stringbatch-filevariablesreturn

How to replace every occurrence of = in a string in batch file


First time post - sorry! Yes, I have seen many posts on how to replace characters in a string in batch script, but I can't seem to make any of them work with "=". Here is what I would like to do:

This is a batch file, running in a bash shell:

set ss=param1=  3, pram2 =  27.3, param3  = 11,
echo %ss% | sed 's/=/ /g' |  sed 's/,/ /g'

it beautifully writes to the screen:

param1   3  pram2    27.3  param3    11 

That is exactly what I would like a variable to be full of, not look at it on a screen! I would like it to write instead to a variable - say, something like:

set sss=echo %ss% | sed 's/=/ /g' |  sed 's/,/ /g'
echo %sss% returns ECHO is off.
echo $sss returns $sss

Thanks very much for your help!


Solution

  • set "ss=param1=  3, pram2 =  27.3, param3  = 11,"
    
    for /f "delims=" %%A in (
        'echo %ss%^|sed "s/=/ /g"^|sed "s/,/ /g"'
    ) do set "sss=%%A"
    
    echo sss: %sss%
    

    In Bash, you can assign the Stdout of a command directly to a variable.

    In CMD, you can use a for /f loop to run a command and return each line of Stdout. The command run needs the | escaped with ^. The arguments of sed may require double quotes instead of single quotes that Bash may use. The delims= option tells the for loop to not delimit each line into tokens.

    View for /? for help about running commands in a for loop.