Login   /   Register

Find and replace text in a text file

Rate this article
     0 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 50 votes, average: 0 out of 5
Loading ... Loading ...
April 1st, 2008 by daniva

Although we can’t directly search and replace text inside a text file, we can do the next best thing. We can: 1) open up a text file; 2) read the text into a variable; 3) do a search-and-replace on that variable; and 4) re-save the text file. We can even do all that from the command line, although we’ll hold off on that for a moment. Instead, let’s start with a simple script that carries out the search and replace:

Const ForReading = 1
Const ForWriting = 2
 
Set fso = CreateObject( "Scripting.FileSystemObject" )
Set textFile = fso.CreateTextFile( "C:\test.txt", ForReading )
 
text = textFile.ReadAll
textFile.Close
 
newText = Replace( text, "QTP ", "QuickTest ")
 
Set textFile = fso.OpenTextFile( "C:\test.txt", ForWriting )
textFile.WriteLine newText
textFile.Close

We start off by creating two constants (ForReading and ForWriting), which we’ll use for the two occasions when we’ll open our text file. (Yes, we said two occasions). We create an instance of the FileSystemObject, and then use the OpenTextFile method to open the file C:\test.txt for reading

With the file open, we use the ReadAll method to read the contents of the entire file into the variable text. We then close C:\text.txt even though we’ll almost immediately reopen it, this time for writing. Seems silly, yes, but that’s the way the FileSystemObject works: you can open a file for reading or you can open a file for writing, but you can’t perform both operations at the same time.

Having stored the contents of the file in the variable text, we then use the VBScript Replace function to replace all instances of QTP with QuickTest. That’s what we do in this line of code:

newText = Replace( text, "QTP ", "QuickTest ")

Next we reopen our file (for writing), call the WriteLine method to write the contents of newText to the file, and then close the file a second time.

Based on "How Can I Find and Replace Text in a Text File?" from the Scripting Guys

Posted in VBScript

Leave a Reply

You must be logged in to post a comment.

This article was viewed 416 times