1

I have three variables: string, search, replace. I wish to substitute the %search% in %string% with %replace%.

This works but needs hard characters.

SET modified=%string:morning=evening%

This seems to be answer in the forums but does not work. It simply stores the entire line at %modified%

SET modified=!string:%search%=%replace%!

1
  • 1
    That syntax only works if you use delayed variable expansion. Use setlocal enabledelayedexpansion at the top of your script, or call your script using cmd.exe /V:ON. Commented Mar 11, 2013 at 2:57

1 Answer 1

1

The ! format is doing delayed expansion--the % variables get expanded immediately, but the ! variable gets expanded only when it's needed. I believe that only works in a batch file, so if you're experimenting directly at the command line you won't get the same behaviour as if you are running a batch file.

Make sure to enable delayed expansion in your batch file before using the ! notation, like this:

SETLOCAL ENABLEDELAYEDEXPANSION
SET string=This morning
SET search=morning
SET replace=evening
SET modified=!string:%search%=%replace%!
ECHO %modified%
ENDLOCAL

This will echo This evening.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Enabling delayed expansion is what I wasn't doing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.