user3784205
user3784205

Reputation: 33

How to find and replace specifc string in txt using .bat?

I have a xml:

    <?xml version="1.0"?>
<arquivoposicao_4_01 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<fundo xmlns="http://tempuri.org/">
<header>

And i just want to replace de string "xmlns=" for anything, like: "dog=".

I am using this .bat:

@echo off
REM -- Prepare the Command Processor --
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.
)

and i use: file.bat "xmlns=" "dog=" nome.txt but it replace "xlmns=" for "=dog=".

PS: i just want replace the third line, the second not.

Upvotes: 0

Views: 168

Answers (2)

Magoo
Magoo

Reputation: 79982

@ECHO Off
REM -- Prepare the Command Processor --
SETLOCAL ENABLEEXTENSIONS
SETLOCAL DISABLEDELAYEDEXPANSION
REM if "%~1"=="" findstr "^::" "%~f0"&GOTO:EOF
:: Replacing parameters with fixed strings for testing
SET "p1=xmlns"
SET "p2=dog"
SET "p3=q24511441.txt"
for /f "tokens=1,* delims=]" %%A in ('"type %p3%|find /n /v """') do (
 set "line=%%B"
 if defined line (
 ECHO("%%B"|FIND "%p1%="
  IF ERRORLEVEL 1 (ECHO(%%B) ELSE (
   call set "line=%%line:%p1%=%p2%%%"
   for /f "tokens=1*delims==" %%X in ('set line') do ECHO(%%Y
  )
 ) ELSE ECHO(
)
GOTO :EOF

Here's a way to do something similar to what you appear to want.

The problem appears to be that the replace-text syntax uses = to separate the target string from the replacement.

Your routine seems to be aimed at being a universal replace-one-string-with-another routine. Batch is not relly suited to this task, but it can be done within limits.

I've replaced your parameters %1..%3 with fixed text for testing. The routine would be used to replace %1= with %2= and is not perfect. It will leave xmlns alone on lines that do not contain xmlns= and replace any xmlns on a line which contains xmlns= with dog.

I used a file named q24511441.txt containing your data for my testing.

Upvotes: 1

dethorpe
dethorpe

Reputation: 521

Replacing a string like this containing an "=" is very problamatic in windows batch as theres no way of escaping or quoting it (that i know of).

See here for some ideas: Escaping an equals sign in DOS batch string replacement command

Also parsing/modifying XML in batch scripts using search/replace and regex for parsing is generally a bad idea, loads of possible problems and issues. Best to write a program in a language that provides XML parsing libraries (e.g java, perl etc).

Upvotes: 0

Related Questions