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]

Thanks
qvhitAsked:
Who is Participating?
 
rajeshgkamathCommented:
Hi,

As you requested to remove the prompts so that it can run silently........here is the new script for the same. Delete everything from replace.vbs and copy the following text instead.

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

FileContents = GetFile(FileName)

dFileContents = replace(FileContents, Find, ReplaceWith, 1, -1, 1)

if dFileContents <> FileContents Then
  WriteFile FileName, dFileContents
Else
  Wscript.Echo "Searched string Not In the source file"
End If

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

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

On the other query, when you export directly from registry as text file it somehow still remembers that it not a pure text format and hence the VB code is not able to read the text file properly instead when it reads the exported text file there are some junk characters coming in the output. So you have to copy / paste the contents in another text file.
0
 
vsg375Commented:
Hi

You may want to check this link :

http://www.ericphelps.com/scripting/samples/

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
Cheers
0
 
qvhitAuthor Commented:
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?

Cheers
0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
rajeshgkamathCommented:
Hi,

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
Else
  '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
0
 
vsg375Commented:
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
Cheers
0
 
qvhitAuthor Commented:
Ok, I have got a batch file that reads

replace.vbs HKEY_LOCAL_MACHINE HKEY_CURRENT_USER C:\Reg.txt

but I'm getting a 'Type mismatch error'

Any ideas?

Cheers
0
 
FishMongerCommented:
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
0
 
qvhitAuthor Commented:
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.

Cheers
0
 
Andrew_CzCommented:
It should work.  Perhaps you haven't entered the syntax in correctly?

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

Then:

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.

0
 
FishMongerCommented:
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
0
 
TribmosCommented:
If its only one file use Wordpad, it has a builtin find/replace.

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

edit -> Replace
-or-
ctrl-h


Good luck,


0
 
vsg375Commented:
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.

Cheers
0
 
rajeshgkamathCommented:
Hi,

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.
0
 
qvhitAuthor Commented:
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
0
 
qvhitAuthor Commented:
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)?
0
 
qvhitAuthor Commented:
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
0
 
Andrew_CzCommented:
Hmm...someone needs to get paid now.
0
 
collegisadminCommented:
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!
0
 
tonuxCommented:
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 !!!
Cheers

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.