Replace substring containing spaces

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
dfashimpaur
Posts: 2
Joined: 08 Feb 2013 13:59

Replace substring containing spaces

#1 Post by dfashimpaur » 08 Feb 2013 14:17

Hello all.

I am trying to create a DOS file which will modify some string data for me. The input strings can be dynamic and the replacement value may need to be empty (no characters) and sometimes it may be a substring containing spaces.

This is essentially what I have:

Code: Select all

@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION

SET originalStr="Some text to be processed. Some text may contain Hello World. Some text may contain nothing worthwhile at all."
SET strToReplace="nothing worthwhile at all"
SET replacementString="very important stuff"

:: I thought this would work.... but it does not

SET str=%originalStr:!strToReplace!=!replacementString!%

ENDLOCAL


Is there anyway to get this to work as I want it to?

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: Replace substring containing spaces

#2 Post by Squashman » 08 Feb 2013 15:23

Code: Select all

@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION

SET originalStr="Some text to be processed. Some text may contain Hello World. Some text may contain nothing worthwhile at all."
SET strToReplace=nothing worthwhile at all
SET replacementString=very important stuff

SET str=!originalStr:%strToReplace%=%replacementString%!

echo %str%
pause

ENDLOCAL

dfashimpaur
Posts: 2
Joined: 08 Feb 2013 13:59

Re: Replace substring containing spaces

#3 Post by dfashimpaur » 08 Feb 2013 16:37

Squashman wrote:

Code: Select all

@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION

SET originalStr="Some text to be processed. Some text may contain Hello World. Some text may contain nothing worthwhile at all."
SET strToReplace=nothing worthwhile at all
SET replacementString=very important stuff

SET str=!originalStr:%strToReplace%=%replacementString%!

echo %str%
pause

ENDLOCAL


Thanks, Squashman. Will it be a problem if replacementString is empty?

Squashman
Expert
Posts: 4488
Joined: 23 Dec 2011 13:59

Re: Replace substring containing spaces

#4 Post by Squashman » 08 Feb 2013 17:01

what is stopping you from answering your own question by at least trying it first.

Post Reply