How to substitute variable contents in a Windows batch file

前端 未结 7 1613
栀梦
栀梦 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:27

    Recently I came accross the same situation..As said earlier, I used like below and worked...

    set filearg=C:\data\dev\log\process
    set env=C:\data\dev
    
    REM I wanted \log\process as output
    
    SETLOCAL enabledelayedexpansion
    set str2=!filearg:%env%=!
    echo Output : %str2%
    echo.
    endlocal
    

    Output :

    \log\process
    

    It worked..!!

    0 讨论(0)
  • 2021-01-08 01:32

    And... How about this?

    @echo off
    setlocal enabledelayedexpansion
    
    set str=The fat cat
    set f=fat
    set t=thin
    
    echo.
    echo       f = [%f%]
    echo       t = [%t%]
    
    echo.
    echo     str = [%str%]
    
    set str=!str:%f%=%t%!
    
    echo str:f=t = [%str%]
    

    Nifty eh?

    0 讨论(0)
  • 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%.

    0 讨论(0)
  • 2021-01-08 01:34

    Please try the following:

    Copy and paste the code into Notepad and save it as a batch file.

       @echo off
       setlocal enabledelayedexpansion
    
       set str=The fat cat
       set f=fat
    
       echo.
       echo          f = [%f%]
    
       echo.
       echo        str = [%str%]
    
       set str=!str:%f%=thin!
    
       echo str:f=thin = [%str%]
    

    I hope you're convinced!

    0 讨论(0)
  • 2021-01-08 01:36

    The problem with:

    echo %a:%c%=thin%
    

    is that it tries to expand two variables: a: and =thin with a c constant string between them.

    Try this:

    echo echo ^%a:%c%=thin^% | cmd
    

    The first command outputs:

    echo %a:fat=thin%
    

    which is piped into a second command shell for evaluation.

    0 讨论(0)
  • 2021-01-08 01:41

    :: Use perl on %var% =~ s/$old/$new/

    set var=The fat cat
    set old=fat
    set new=thin
    
    ECHO before=%var%
    
    for /f "delims=" %%m in ('echo %var% ^|perl -pe "s/%old%/%new%/" ') do set var=%%m
    
    ECHO after=%var% 
    

    Output:

    before=The fat cat
    after=The thin cat
    
    0 讨论(0)
提交回复
热议问题