Articles

Find and Replace text in Batch File

March 16, 2005 at 18:06:01
Specs: Windows XP/2003, 3.0Ghz

I need to figure out a method to find and replace text within a text file.

I have a file named, "myfile.txt" that has the following;

testing=1
database=500
rules=30

I want the batch file to find database=500 and insert destination=300 under it.

I want it to look like this;

testing=1
database=500
destination=300
rules=30

I'll be using the NT platform for this. (NT,2000,XP,2003)

Thanks

MagnumVP


See More: Find and Replace text in Batch File

Report •


#1
March 17, 2005 at 00:40:27

The following batch for NT systems fits your need

For /F "tokens=1,2 delims==" %%A in (%1) Do (
Echo %%A=%%B>> %1.tmp
If "%%A"=="database" (
Echo destination=300>> %1.tmp))
Move %1.tmp %1

I named it Atxt.bat and to run just type

Atxt Pathname/FileName (e.g. Atxt Myfile.txt)


Report •

#2
March 17, 2005 at 13:50:20

That gets me REALLY close. I appologize, I forgot one portion of the file. There is a [configuration] along with it, that seems to be messing with the batch.

Here is what it was;

[configuration]
testing=1
database=500
rules=30

Here is what I get; Is there a way to get the "=" from after the [configuration]?

[configuration]=
testing=1
database=500
destination=300
rules=30

ALSO... Is there a way to assign variables so you don't have to pull it from %1?

Example:

SET Filename=Myfile.txt
For /F "tokens=1,2 delims==" %%A in (%Filename%) Do (
Echo %%A=%%B>> %Filename%.tmp
If "%%A"=="database" (
Echo destination=300>> %Filename%.tmp))
Move %Filename%.tmp %Filename%

Thanks

MagnumVP


Report •

#3
March 17, 2005 at 15:37:40

Hi Magnum
Doe's this help

@echo off
if exist newfile.txt del newfile.txt
for /f "tokens=*" %%a in (myfile.txt) do call :AddText "%%a
del myfile.txt
rename newfile.txt myfile.txt
exit /b

:AddText %1
set Text=%~1%
echo %Text% >> newfile.txt
if "%Text%"=="database=500" echo desination=300 >> newfile.txt
exit /b


Report •

Related Solutions


Ask Question