String replacement in batch file

后端 未结 4 1630
夕颜
夕颜 2020-11-28 22:46

We can replace strings in a batch file using the following command

set str=\"jump over the chair\"
set str=%str:chair=table%

These lines wo

相关标签:
4条回答
  • 2020-11-28 23:29

    This works fine

    @echo off    
    set word=table    
    set str=jump over the chair    
    set rpl=%str:chair=%%word%    
    echo %rpl%
    
    0 讨论(0)
  • 2020-11-28 23:39

    You can use !, but you must have the ENABLEDELAYEDEXPANSION switch set.

    setlocal ENABLEDELAYEDEXPANSION
    set word=table
    set str="jump over the chair"
    set str=%str:chair=!word!%
    
    0 讨论(0)
  • 2020-11-28 23:39

    You can use the following little trick:

    set word=table
    set str="jump over the chair"
    call set str=%%str:chair=%word%%%
    echo %str%
    

    The call there causes another layer of variable expansion, making it necessary to quote the original % signs but it all works out in the end.

    0 讨论(0)
  • 2020-11-28 23:48

    I was able to use Joey's Answer to create a function:

    Use it as:

    @echo off
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    SET "MYTEXT=jump over the chair"
    echo !MYTEXT!
    call:ReplaceText "!MYTEXT!" chair table RESULT
    echo !RESULT!
    
    GOTO:EOF
    

    And these Functions to the bottom of your Batch File.

    :FUNCTIONS
    @REM FUNCTIONS AREA
    GOTO:EOF
    EXIT /B
    
    :ReplaceText
    ::Replace Text In String
    ::USE:
    :: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
    ::Example
    ::SET "MYTEXT=jump over the chair"
    ::  echo !MYTEXT!
    ::  call:ReplaceText "!MYTEXT!" chair table RESULT
    ::  echo !RESULT!
    ::
    :: Remember to use the "! on the input text, but NOT on the Output text.
    :: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
    :: ^^Because it has a ! around the chair table and RESULT
    :: Remember to add quotes "" around the MYTEXT Variable when calling.
    :: If you don't add quotes, it won't treat it as a single string
    ::
    set "OrginalText=%~1"
    set "OldWord=%~2"
    set "NewWord=%~3"
    call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
    SET %4=!OrginalText!
    GOTO:EOF
    

    And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

    SETLOCAL ENABLEDELAYEDEXPANSION
    @REM # Remember to add this to the top of your batch file.
    
    0 讨论(0)
提交回复
热议问题