Page 1 of 1

Batch script text replace issue

Posted: 21 Nov 2012 01:17
by abhi130182
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.
)

Re: Batch script text replace issue

Posted: 21 Nov 2012 01:46
by jeb
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