Dos Function "substitute" does not work, here is a fix

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
McNetic
Posts: 1
Joined: 21 Jan 2015 09:08

Dos Function "substitute" does not work, here is a fix

#1 Post by McNetic » 21 Jan 2015 09:16

Hello,

I found the function "substitute" appears to be a simple c&p from the sample script "BatchSubstitute.bat". Afaics, the latter should work as expected (I did not try), but the function does not work as desired. First, it misses ENABLEEXTENSIONS, and secondly, it does only output the new file contents on stdout. So I fixed it to do as desired:

Code: Select all

:substitute OldStr NewStr File -- substitutes a string in a text file
::                             -- OldStr [in] - string to be replaced
::                             -- NewStr [in] - string to replace with
::                             -- File   [in] - file to be parsed
:$created 20060101 :$changed 20150121 :$categories FileManipulation
:$source http://www.dostips.com
SETLOCAL DISABLEDELAYEDEXPANSION
SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v ""&&BREAK>%3"') do (
    set "line=%%B"
    if defined line (
        call set "line=echo.%%line:%~1=%~2%%"
        for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X>>%3
    ) ELSE echo.>>%3
)
EXIT /b


This works, at least on my Win7.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Dos Function "substitute" does not work, here is a fix

#2 Post by Ed Dyreen » 21 Jan 2015 09:47

Guess enableExtensions is left out because extensions are enabled by default.

Code: Select all

set "$err=0"    %=   custom error      =%

rem Assuming winME/2000 or above
echo. 'enableExtensions'
2>nul verify error %=    must set initial errorlevel non zero      =%
setlocal enableExtensions
rem (
       if errorlevel 1 set "$err=Extentensions could not be enabled, this program cannot continue."
       if not "%$err%" == "0" goto :§EndOldOS "()"
rem )
endlocal

setlocal enableExtensions

Post Reply