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

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
strNewText = Replace(strText, "Jim ", "James ")

Set objFile = objFSO.OpenTextFile("C:\Scripts\Text.txt", ForWriting)
objFile.WriteLine strNewText

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
strNewText = Replace(strText, strOldText, strNewText)

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

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 "

Comments (66)

  1. UmeshMishra says:

    Can I use this script to change the text in a java script. Actually I need to make changes to file called prefs.js located at "C:UsersusernameAppDataRoamingMozillaFirefoxProfilesyce2e09c.default"

    The challenge is the name of the last folder (yce2e09c.default) is different for every user profile ( like xce2d09c.default, zce5f09s.default, ygh2e10c.default etc)

    I want to use this script to change some text (user_pref("", true);) to user_pref("", false);

    Please help.

  2. AlokKr says:

    This should work : (Get-Content ‘C:ScriptsText.txt’) | foreach {$_.ToString().Replace(‘Jim’,’James’)} | Set-Content ‘C:ScriptsText.txt’

  3. Anonymous says:

    You are adding an extra CRLF to the end of the file. Use Write instead.

  4. Anonymous says:

    Ahmad, you need to have the file C:ScriptsText.txt or the script will not work.

  5. AHMAD says:

    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?

  6. kai says:

    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!

  7. Katie says:

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

  8. Mickey says:

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

  9. thanks says:

    This works. Thanks a lot for the script.

  10. JP says:

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

  11. Mattias Ahlin says:

    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,


  12. Chris says:

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

  13. jaden says:

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

  14. kstephens says:

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

    "objFile.WriteLine strNewText"


    "objFile.Write strNewText"

    This clears up the "extra line" problem.

  15. Rick says:

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

  16. Demacia says:

    Works like a charm; thanks!

  17. Erik says:

    This is Awsome.  I love this example

  18. Tux says:

    Much, much easier on UNIX. Only takes 1 line.

  19. Mary Connor says:

    Brilliant and helpful! But how do I search/replace terms that contain quotes?

  20. Cmen007 says:

    Awesome I needed this. I was just wondering how could I get this to search through multiple directories such as:

    file to change is toor


    there is only one folder that will change each time other then that I know the rest.

    Any help would be great!

  21. Ahmad Belal says:

    Thanks. You helped me a lot, but I also want to replace an entire line with another ignoring what words in it. Could you help me?

  22. Dianne says:

    On Word 7, I used to be able to press Control and hit the F key to get a simple "find and replace" feature.  In the "find" box, type in the word or name already in the document, then in the replace box type in the new name.  Hit enter.  Viola, every instance of the name or word I no longer wanted in my document was replaced with the new name.  Word 10 is a joke.  I would not recommend it to anyone.  It is no longer user friendly and the steps you have described for your new "find and replace" feature are ridiculous. You guys need to enter the real world and find out what users really want.  

  23. kumar says:

    Thanks Very much, your article was very helpful!

  24. Manish says:

    its a good script and working fine.

  25. Jomy says:

    Works fine with all other varchar, But I have a Q , how can I replace   "  from a doc ?

  26. daisy4 says:

    How about if there is " (quote) mark in the replace test? I didn't work for me.

  27. JV says:

    How to replace quotes in a file.

    ' Command line can contain instructions

    ' EXAMPLE:  replace /search:Chr(34) /replace:QUOTE


    strFileName = Wscript.Arguments(0)

    strOldText = Eval(Wscript.Arguments.Named.Item("search"))

    strNewText = Wscript.Arguments.Named.Item("replace")

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set objFile = objFSO.OpenTextFile(strFileName)

    strText = objFile.ReadAll()


    strNewText = Replace(strText, strOldText, strNewText)

    Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)

    objFile.WriteLine strNewText


  28. thanksguys says:

    @JV … your solution to remove QUOTES brought tears to me. I was going into loops on how to remove quotes because I can't use the (") in a string prompt. thanks man!

  29. Jtoon says:

    So, I found this script to be VERY helpful.  However, if I try to use it in a batch file, and the text I try to replace has what looks like a variable, say, "%stuff%in this folder" the batch file will skip the %stuff% portion, and only replace the "in this folder" portion.  If I run the replace command manually, from a command line, I don't have this problem, and the entire string (including %stuff%)gets replaced as expected.  Would anyone happen to have any clues for solving this?

  30. Graham says:

    Very nice, how difficult would it be to replace the text in several files within a directory say all the .txt files?

  31. bill says:

    Is there any way to do all this straight through the Command Prompt window. Not using a third party scripting program.

  32. Hi says:

    I used the script to remove "" from my file. the file is 95MB csv. the script fails giving an error of out of resources. how can i read one line and replace chracters and write that line to another file immediately?/


  33. jay says:

    I am using this script and got everything to work great until I tried to make some modifications. I am trying to read some text from an excel file and use variables for the text to be replaced and the text to replace it with. Here is the loop I am using:

    i = 1

    Do Until objXl.Cells(i,1).Value = ""

    PIVOld = objXl.Cells(i,2).Value

    PIVNew = objXl.Cells(i,3).Value

    strNewText = Replace(strText, PIVOld, PIVNew)

    i = i + 1


    I know the variables are being set because I added some message boxes in it and they changed to the correct values each time, however, I do not think the Replace is working. When I open the text file, nothing has changed.

    Can anyone suggest anything? Thank you.

  34. First Time Scripter says:

    Awesome information. Works like a charm. Very well explained. I am novice, but was able to make the changes I needed to make to the script to suit my requirement. Do you have a way to do this on multiple files?

    Thank you very much.

  35. Jhonatan Aguilar Benavides says:

    hello, how do I use this script to modify the host file, I could not because the file does not have a host extension.

    please help me with this query

  36. Violet says:

    For hosts file, just use

    strSrcFile = "C:<where hostsfiles are located>hosts"

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    set objFile = objFSO.OpenTextFile(strSrcFile, 1, false)

    That will work. No need for an extenstion.

  37. Violet says:

    What if the I want to replace the exact string.. and not the substring. For example:

    JimJones Smart <—– Do not replace this.

    Mary Smith

    Jim Carsh <— I only want to replace this.

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

    This makes the file:  (it replaces both instance of "Jim"

    JamesJones Smart

    Mary Smith

    James Carsh

    Any idea?

  38. AMEEN says:

    I tried it and it works! However, it did not work when I actually wanna use it. I got the following runtime error : name redefined: 'ForReading'

  39. Sathishg1 says:

    I need a vbscript that reads a 34th line one txt file and overwite it on 32nd line of another txt file… Please help me …

  40. RavikanthC says:

    Wonderful explanation!!! Cant go wrong.

  41. multiple files says:

    How can we use this to run through multiple files in a directory.  I see you have to specify the filename, but what if the directory had 20 files in it.  Can someone share how we would go about modifying this to have it search multiple files?

  42. gaurav says:

    i am using this exact script,but it is not replacing.
    No erros either

    Const ForReading = 1
    Const ForWriting = 2

    Set objFSO = CreateObject(“Scripting.FileSystemObject”)
    Set objFile = objFSO.OpenTextFile(“C:ScriptsText.txt”, ForReading)

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

    Set objFile = objFSO.OpenTextFile(“C:ScriptsText.txt”, ForWriting)
    objFile.WriteLine strNewText

  43. Steve K. says:

    Thanks for the script. But there is "Microsoft console based script host has stopped working" on windows server 2008 R2. Who can propose a version for windows server 2008 R2

  44. BarnieRubble says:

    This worked great for me, but i ran into an issue. What if the field had already been modified? My example is this…
    I have a text file with the word “change” in it once, at the beginning of a line, and I want to make it say “–change”.
    Suppose I need to change this across a lot of machines, and I have already manually modified some.
    Then, when I run the script across the entire enterprise, I get some files that will say this “—-change”, because the script looks for “change”, not ” change”.
    What can I do to the script to prevent this?

  45. DCab says:

    this is great! any way to have it look for/replace different words or be able to feed the script a csv file with what to look for and what to change it to?

  46. Oliver says:


    I was wondering if anyone can help. I need to search if line contain some text and replace the text next to it.

    [Print Default]
    Device Name=YourLocalPrinter (redirected 44)
    Port: TS222

    In my case, I would like to replace "YourLocalPrinter (redirected 44)" by something else.


  47. Flore says:

    Hi and thanks for the script. I am able to use the revised script from the prompt command but I do not get how to implement the first script… Thanks a lot in advance to answer to a stupid question…
    I would like to make some changes into the code to achieve what I need.

  48. Abhiram says:

    How about this.

    Notes = John
    notesctl.value = notesctl.value.Replace(", John","Johny")
    Output = Johny

  49. Abhiram from Chitradurga says:

    How about this.

    Notes = John
    notesctl.value = notesctl.value.Replace(", John","Johny")
    Output = Johny

  50. Abhay says:

    I tried the script and it worked for all the instances except for the work i wanted to replace. this i need to replace with a blank entry.

    How to do this. Any help will be great.
    Thanks in advance

  51. Anonymous says:

    Awsome!! I waorked with the script for 4 hours and charged 80 hours

  52. aaron says:

    Hi, This script is just what im looking for however I would like to run this against a number of text files within a set folder, If use the usual "for %%a in….." in cmd i get a subscript out of range error. Any ideas how i should go about this?

  53. rodrigo says:

    it was easy to understand. Thank you.

  54. Neel says:

    Hello every one,
    Script is working but i want to add multiple lines,Please help me

  55. Jeff D says:

    Awesome article, very helpful!

  56. Sandip says:

    This is very useful post. Thanks!

  57. Suneel says:


    Need some help…
    My requirement is something like this

    Jim 1 3 4 6
    Jim 1 2 3 1
    Should be repalced with Jim 1 0 0 1

    Is there a possibility to fine tune this script#?

  58. ric says:

    how can run a search for a file to replace the text? I have couple of OS’s that have different directory structures (XP, Win7) the same file I want to change keywords on resides in two different locations….Thanks

  59. Karthiga says:

    Hi ,

    Am getting "Type mismatch " error .Please help me with this.


    Set objFileToWrite = CreateObject("Scripting.FileSystemObject")
    set writobj=objFileToWrite.OpenTextFile("C:exampOrder.txt",2)

  60. Anul says:

    Good one. Can any one help for my issue. I have a txt file and need to replace a word. Example, the word actdtyhbvcf should be changed to act. I need first 3 chars to be as new word. Because I have mutilple entries starts with act.

  61. anonymous says:

    I’d use a "outputSplit = split(text, "Jim")" instead ant then transform it into a string
    "outputSplit = split(text, "Jim")"

    outputString = ""
    for each i in outputSplit
    outputString = outputString & "James" & outputSplit(i)


    However, keep in mind it won’t work when the text starts with "Jim"…

  62. Skl816405 says:

    Hey, Scripting Guy!

    I need to replace (;"EE) TO (;"E)

    I hope that you can help

    Best regards

  63. ivan says:

    Any chance for something like this… I have txt file with lot of text and constant number repeating.
    3#text#1200000112#some text#9899#text
    3#text#1200000112#some text#9899#text
    3#text#1200000112#some text#9899#text

    Now what I need is script to find each 1200000112 and replace every time with +1

    3#text#1200000113#some text#9899#text
    3#text#1200000114#some text#9899#text
    3#text#1200000115#some text#9899#text

  64. Marcelo says:

    Excellent. I would like to change a text by the hostname (server name)

  65. Umeed4u says:

    In VBSCript. …how to check different strings and replace them with new ones.
    For example my file has a line


    and i want them to be replaced by

    Please advise

Skip to main content