Help with BatchSubstitute.bat

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
SMA
Posts: 2
Joined: 06 Jul 2010 16:52

Help with BatchSubstitute.bat

#1 Post by SMA » 06 Jul 2010 17:10

I am using the following BatchSubstitue.bat file to find and replace a string in a text file:

Code: Select all

@echo off
REM -- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

::BatchSubstitude - parses a File line by line and replaces a substring"
::syntax: BatchSubstitude.bat OldStr NewStr File
::          OldStr [in] - string to be replaced
::          NewStr [in] - string to replace with
::          File   [in] - file to be parsed
:$changed 20100115
:$source http://www.dostips.com
if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF
for /f "tokens=1,* delims=]" %%A in ('"type %3|find /n /v """') do (
    set "line=%%B"
    if defined line (
        call set "line=echo.%%line:%~1=%~2%%"
        for /f "delims=" %%X in ('"echo."%%line%%""') do %%~X
    ) ELSE echo.
)


I am trying to replace a parameter in a text file that looks like this:
FlagA = 13
FlagB = 2
FlagC = 3
FlagD = 0
etc.

I would like to reset the value of FlagC from 3 to 1.

I use the BatchSubstitue.bat file with the following command line:
BatchSubstitute.bat "FlagC = 3" "FlagC = 1" test.txt > test2.txt

However, I get the following undesirable result:
3=FlagC = 1= 3

Is there any easy way to fix this problem?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Help with BatchSubstitute.bat

#2 Post by aGerman » 07 Jul 2010 10:42

Hmm, seems that the equals-sign causes this fault.
I wrote a different batch file for you.

ReplaceParam.bat

Code: Select all

@echo off &setlocal
:: syntax:
:: call ReplaceParam.bat Flag NewValue Filename

if not exist "%~3" goto :eof
set "flag=%~1"
set "newval=%~2"
set "tempFile=%temp%\ReplaceParam.tmp"
>"%tempFile%" type nul
for /f "delims=: tokens=1*" %%a in ('findstr /n "^" "%~3"') do (
  set "line=%%b"
  call :proc
)
move /y "%tempFile%" "%~3"
goto :eof

:proc
if not defined line (
  >>"%tempFile%" echo.
  goto :eof
)
echo.%line%|findstr /b /i /c:"%flag% =" >nul &&(
  >>"%tempFile%" echo.%flag% = %newval%
)||(
  >>"%tempFile%" echo.%line%
)
goto :eof



Try the following command line:
call ReplaceParam.bat FlagC 1 test.txt

ATTENTION The batch file will overwrite the source file. Hope this will be OK for you.

Regards
aGerman

SMA
Posts: 2
Joined: 06 Jul 2010 16:52

Re: Help with BatchSubstitute.bat

#3 Post by SMA » 12 Jul 2010 10:43

Thank you! This works perferctly!

This was an enormous help.

Best regards,
SMA

Post Reply