Batch script text replace issue

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
abhi130182
Posts: 2
Joined: 21 Nov 2012 00:48

Batch script text replace issue

#1 Post by abhi130182 » 21 Nov 2012 01:17

Hi Guys,

I have to write a batch file which will replace the matching word from the text file. everything is fine with below script except a character '[' deletes from new created file.
I am using this script to replace my old value to new value but delims value ] is also deleted from the new file.

Please guild me how can I replace the text without deleting any character value.

@echo Off
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

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.
)

jeb
Expert
Posts: 1062
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: Batch script text replace issue

#2 Post by jeb » 21 Nov 2012 01:46

The problem is here the delim character, as it will split the line at the first delim character found and remove it but also any amount of directly following delim characters.

So for a line like "[1]]]]]]]]]]]]Hello" you will get only "Hello".

Solution: Don't use delims here.

Code: Select all

@echo Off
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION

if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF
for /f "tokens=1,* delims=" %%A in ('"type %3|find /n /v """') do (
  set "line=%%B"
  SETLOCAL EnableDelayedExpansion
  set "line=!line:*]=!"
  if defined line (
    set "line=echo(!line:%~1=%~2!"
  )
  echo(!line!
  endlocal
)


Using delayed expansion here is much more secure, but you need to toggle it each round, else you could loose exclamation marks.

jeb

Post Reply