How to substitute variable contents in a Windows batch file

前端 未结 7 1674
栀梦
栀梦 2021-01-08 00:55

I\'m writing a simple script to substitute text in an environment variable with other text. The trouble I get is with the substituted or substituted text being pulled from o

7条回答
  •  长情又很酷
    2021-01-08 01:33

    Use CALL. Put the following in a batch script and run it:

    set a=The fat cat
    set b=fat
    set c=thin
    
    REM To replace "%b%" with "%c%" in "%a%", we can do:
    call set a=%%a:%b%^=%c%%%
    echo %a%
    pause
    

    As stated here, we use the fact that:

    CALL internal_cmd

    ...

    internal_cmd Run an internal command, first expanding any variables in the argument.

    In our case internal_cmd is initially set a=%%a:%b%^=%c%%%.

    After expansion internal_cmd becomes set a=%a:fat=thin%.

    Thus, in our case running

    call set a=%%a:%b%^=%c%%%

    is equivalent to running:

    set a=%a:fat=thin%.

提交回复
热议问题