How Can I Find and Replace Text in a Text File?

How Can I Find and Replace Text in a Text File?

  • Comments 46
  • Likes
Hey, Scripting Guy! Question

Hey, Scripting Guy! From the command line, how can I use a script to open a file and replace text; for example, how can I replace all instances of “Jim” with “James”?

-- JW

SpacerHey, Scripting Guy! AnswerScript Center

Hey, JW. As we’ve found out numerous times when dealing with text files, there is no obvious way to do this; that is, there is no ReplaceText command that can open a text file and find and replace text. Fortunately, this problem is typical of text file questions in one other respect: although there’s no obvious way to carry out the task, we can still find a way to get the job done.

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 objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Scripts\Text.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Jim ", "James ")

Set objFile = objFSO.OpenTextFile("C:\Scripts\Text.txt", ForWriting)
objFile.WriteLine strNewText
objFile.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:\Scripts\Text.txt for reading.

With the file open, we use the ReadAll method to read the contents of the entire file into the variable strText. We then close C:\Scripts\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. (As you should know by now, the FileSystemObject works in mysterious ways.)

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

strNewText = Replace(strText, "Jim ", "James ")

Notice that we’re looking for each instance of "Jim " (Jim followed by a blank space) and replacing those with "James " (James followed by a blank space). Though hardly foolproof, this gives our script a tiny bit of intelligence; if the script encounters the name Jimmy it won’t try to replace the Jim with James (resulting in Jamesmy). The new file we create - the one where each Jim has been replaced by James - is stored in memory in the variable strNewText.

Next we reopen our file (for writing), call the WriteLine method to write the contents of strNewText to the file, and then close the file a second time. The net effect? If we started off with a text file that looked like this:

Jim Jones
Mary Smith
Jim Doe
Jim Johnson
Mary Johnston

we’ll end up with a text file that looks like this:

James Jones
Mary Smith
James Doe
James Johnson
Mary Johnston

As for doing this all from the command-line, we simply need to modify the script so that it will accept - in this order - three command-line arguments: the name of the file to open; the text we want to search for; and the text we want to replace. Here’s a script that does just that. Note that we store the command-line arguments in the variables strFileName, strOldText, and strNewText, and we use those variables when opening and saving the text file and when calling the Replace function:

Const ForReading = 1
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, strOldText, strNewText)

Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.WriteLine strNewText
objFile.Close

To use this revised script (which we’ll call replace.vbs) just type a command similar to this from the command prompt:

cscript replace.vbs "C:\Scripts\Text.txt" "Jim " "James "

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • You are adding an extra CRLF to the end of the file. Use Write instead.

  • Hi and thx for the support.

    Tried your script but no luck? error message is stated below:

    Line: 5

    Character: 1

    Error: File not found

    can you help pls?

  • Ahmad, you need to have the file C:\Scripts\Text.txt or the script will not work.

  • OK I just used the revised script on a project I was working on and it worked flawless. THANKYOU!!!

    I was able to parse a text file to remove , (commas) to .(full stop) and then reparse the file to change | (bang) to , (commas) so it could be a csv file.

    Thanks again!

  • How can you search and ignore case? Or do wildcards in my searches ? Like if I was search a uncpath \\machineX\sharename, sharename will be fixed but machineX will vary.. do \\?\sharename

  • Superb and by changing the writeline to write made this a suprb script to run.  Thank you for sharing

  • This works. Thanks a lot for the script.

  • I am not working in VB stream but this script helped me to quickly solve my problem. Thanks a TON for the script.

  • Hi and thanks for the script!

    However, the script adds one extra linefeed character at the bottom of the file every time the script is run. Is there a way to prevent that? I just want to replace the text, not add any extra lines to the end of the file.

    Best regards,

    Mattias

  • HI thanks for script. how can i use script for find string and replace entire line ?

  • What if its case sensitive, How would you be able to distinguish from upper case to lower case.

  • To expound on what paulcerv said, replace the line that says,

    "objFile.WriteLine strNewText"

    with

    "objFile.Write strNewText"

    This clears up the "extra line" problem.

  • This works great!  It solved a problem for me.  One more question is there a way to get it to stop after one occurance?

  • Works like a charm; thanks!

  • This is Awsome.  I love this example