Avatar of qvhit
 asked on

Find and replace text string using batch file

Can anyone tell me how I go about getting a batch file to look for a particular text string in a file and then replacing it with something else?

I am exporting part of the registry into a text file and would like HKEY_LOCAL_MACHINE to become HKEY_CURRENT_USER wherever it exists.

For example I would like [HKEY_LOCAL_MACHINE\User\Network\I] to become[HKEY_CURRENT_USER\User\Network\I]

Operating Systems

Avatar of undefined
Last Comment

8/22/2022 - Mon


You may want to check this link :


more specifically the SearchAndReplace script. With this one, you can easily create a customizable batch file where you define the parameters you need to change.

You can also customize the vbs script to check for existing strings and replace them, but I'm not sure that will be necessary, since the script will return an error if the string doen't exist, and will replace it with whatever arguments you have passed to the command line if the string does exist.

I hope that helps

Thanks for the quick response.  I shall take a look at that but do you happen to know if the same can be achieved with a MS-DOS command?



There is no find/replace option available in MS DOS commands so it is not possible in Batch script. Alternativelyyou can use the VBS script. Copy the following script in notepad session and save it as .vbs (may be replace.vbs)

Dim FileName, Find, ReplaceWith, FileContents, dFileContents
Find         = WScript.Arguments(0)
ReplaceWith  = WScript.Arguments(1)
FileName     = WScript.Arguments(2)

'Read source text file
FileContents = GetFile(FileName)

'replace all string In the source file
dFileContents = replace(FileContents, Find, ReplaceWith, 1, -1, 1)

'Compare source And result
if dFileContents <> FileContents Then
  'write result If different
  WriteFile FileName, dFileContents

  'Wscript.Echo "Replace done."
  If Len(ReplaceWith) <> Len(Find) Then 'Can we count n of replacements?
    Wscript.Echo _
    ( (Len(dFileContents) - Len(FileContents)) / (Len(ReplaceWith)-Len(Find)) ) & _
    " replacements."
  End If
  'Wscript.Echo "Searched string Not In the source file"
End If

'Read text file
function GetFile(FileName)
  If FileName<>"" Then
    Dim FS, FileStream
    Set FS = CreateObject("Scripting.FileSystemObject")
      on error resume Next
      Set FileStream = FS.OpenTextFile(FileName)
      GetFile = FileStream.ReadAll
  End If
End Function

'Write string As a text file.
function WriteFile(FileName, Contents)
  Dim OutStream, FS

  on error resume Next
  Set FS = CreateObject("Scripting.FileSystemObject")
    Set OutStream = FS.OpenTextFile(FileName, 2, True)
    OutStream.Write Contents
End Function

How to use:
Execute the following command to replace all the occurances of text1 with text2 in the test.txt file

replace.vbs text1 text2 test.txt
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy

rajeshgkamath is right...and not quite right ;o)

the replace function indeed does not exist in batch files. So, what you would have to do could be :

- examine each line of the text file (possible)
- if the text line needs to be left "as is", paste it into a new text file (still possible, but now you have two different text files, heavier to deal with)
- if the text line needs to be modified, modify it accordingly and append it to the newly created file. (same as above)

This is very heavy handing, when a simple vbs script can do the trick flawlessy.

So my answer to your second post would be : what you want to achieve COULD be done in MS-DOS mode, with strong limitations and a very poor flexibility, that is why I advise to use VBS, which is much more flexible.

Hope this helps

Ok, I have got a batch file that reads


but I'm getting a 'Type mismatch error'

Any ideas?


I can't help with the 'Type mismatch error' error, but if you want another option, here's a Perl command that does the substitution and is only 1 line of code.

perl -ni.bak -e "s/HKEY_LOCAL_MACHINE/HKEY_CURRENT_USER/ig" C:\Reg.txt
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.

Thanks FishMonger but I'll try and stick with DOS or VBS for now as it's to go with other stuff I'm doing and would like to keep the changes to a minimum.

Your way does look very simple though so might have to do a re-think if I can't get it working.


It should work.  Perhaps you haven't entered the syntax in correctly?

Download: http://www.ericphelps.com/scripting/samples/SearchAndReplace/SearchAndReplace.vbs


start searchandreplace.vbs filename.txt "texttobereplaced" "replacementtext"

Do this from the directory that has your .txt file.

The quotes are not necessary but helps if you add other characters like a space.


When you're ready to re-think your approach, Perl is free, open source, more concise, and can easily be incorporated into the "other stuff" you're doing.

You can download Perl from http://activestate.com/Products/ActivePerl/?mp=1
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck

If its only one file use Wordpad, it has a builtin find/replace.

Should be on the 'open with' option
use 'run' and type in wordpad  then open the file you want

edit -> Replace

Good luck,


Hi Tribmos, hi all

Interesting solution, but I'm not quite sure our friend is asking for help for just one file that needs to be modified one time, one day. I mean, if every morning, you have to open the file in Wordpad, search for the string, replace it, and make sure it works,multiply that by the number of files you have to wirk on, and either you wind up hanging yourself to a Cat 5 cable (Cat6 works fine too, but a little more expensive... ;o)  or you seriously consider reconversion in the restaurant business....

I guess our friend is talking about a procedure that would help him handle these modifications on a daily basis, maybe weekly, maybe monthly....Well, if it's monthly, I guess you're right to mention WordPad because that's what I would do ;o)

My final opinion is that FishMongers's post is the closest one : depending on the approach, the solution may vary.



If you are using replace.vbs as mentioned in my previous post and still getting error, try following.

1. Do not change anything in Replace.vbs file
2. Only change which you have to do now is open C:\Reg.txt, copy the entire text, open new notepad session, paste the text that you have copied and then save this file as temp.txt.
3. Now execute the replace.vbs command on the new temp.txt file. Once the file is updated rename it to .reg and then update the registry.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.

rajeshgkamath, I have come back to this today and for some bizarre reason it now seems to be working?!

Can the VBS file be edited to get rid of the confirmation of replacements, I'd like it to run silently.

Many thanks

Ok, I remembered what I did differently.  I copied the text from my txt file into another one called temp.txt as suggested and then it worked.

Does anyone know why it won't work if I export part of the registry to a txt file by the same name (temp.txt)?

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

Cheers for the modified script.  To get round the issue of exporting from the registry to a text file I have then got the batch file to write to another text file.  Long winded but it works so I'm happy.

Thanks for all your help
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.

Hmm...someone needs to get paid now.

I found this thread interesting and a coworker of mine found a solution to the problem with copying/pasting to a file with the batch script that will remove the special characters (junk) so that you can do a find/replace.  

If you use DOS command of "type filename > newfilename"  this will allow you to do file and replace on the newfilename.  If you were doing this in a VBSCRIPT, you could do something like:

WshShell.Run("CMD /C type oldfile.reg > newfile.reg")

Thanks for the help in this thread as I was fighting the find/replace in a reg export for days!

Hi collegisadmin,

Many thanks for your last comment. I was just getting mad about doing string replacement in a registry export. the WshShell.Run("CMD /C type oldfile.reg > newfile.reg") just removed any unwanted characters !!!

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.