다음 명령을 사용하여 배치 파일의 문자열을 바꿀 수 있습니다.
set str="jump over the chair"
set str=%str:chair=table%
이 선은 잘 작동하며 문자열 “의자 위로 점프”를 “테이블 위로 점프”로 변경합니다. 이제 문자열에서 “chair”라는 단어를 변수로 바꾸고 싶은데 어떻게해야할지 모르겠습니다.
set word=table
set str="jump over the chair"
??
어떤 아이디어?
답변
!를 사용할 수 있지만 ENABLEDELAYEDEXPANSION 스위치가 설정되어 있어야합니다.
setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%
답변
다음과 같은 작은 트릭을 사용할 수 있습니다.
set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%
는 call
이, 변수 확장의 또 다른 레이어를 일으키는 것이 필요 원본 인용 할 수있게 %
표시를하지만 모두가 결국 밖으로 작동합니다.
답변
Joey ‘s Answer를 사용하여 함수를 만들 수있었습니다.
다음과 같이 사용하십시오.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!
GOTO:EOF
그리고 이러한 기능은 배치 파일의 맨 아래에 있습니다.
: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
그리고 배치 파일 맨 위에 “SETLOCAL ENABLEDELAYEDEXPANSION”을 추가해야합니다. 그렇지 않으면이 중 어느 것도 제대로 작동하지 않습니다.
SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.
답변
이것은 잘 작동합니다
@echo off
set word=table
set str=jump over the chair
set rpl=%str:chair=%%word%
echo %rpl%