Solved

Find and replace text string using batch file

Posted on 2005-12-28
19
52,654 Views
Last Modified: 2012-09-15
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
0
Comment
Question by:qvhit
  • 6
  • 3
  • 3
  • +5
19 Comments
 
LVL 9

Expert Comment

by:vsg375
ID: 15561456
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
 

Author Comment

by:qvhit
ID: 15561468
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
 
LVL 4

Expert Comment

by:rajeshgkamath
ID: 15561916
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:vsg375
ID: 15562219
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
 

Author Comment

by:qvhit
ID: 15562235
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
 
LVL 28

Expert Comment

by:FishMonger
ID: 15562289
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
 

Author Comment

by:qvhit
ID: 15562341
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
 
LVL 3

Expert Comment

by:Andrew_Cz
ID: 15563009
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
 
LVL 28

Expert Comment

by:FishMonger
ID: 15563346
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
 
LVL 6

Expert Comment

by:Tribmos
ID: 15564966
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
 
LVL 9

Expert Comment

by:vsg375
ID: 15565776
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
 
LVL 4

Expert Comment

by:rajeshgkamath
ID: 15569098
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
 

Author Comment

by:qvhit
ID: 15569427
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
 

Author Comment

by:qvhit
ID: 15569514
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
 
LVL 4

Accepted Solution

by:
rajeshgkamath earned 125 total points
ID: 15569628
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
 

Author Comment

by:qvhit
ID: 15569766
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
 
LVL 3

Expert Comment

by:Andrew_Cz
ID: 15570893
Hmm...someone needs to get paid now.
0
 

Expert Comment

by:collegisadmin
ID: 20541471
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
 
LVL 1

Expert Comment

by:tonux
ID: 24393615
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

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I don't know if many of you have made the great mistake of using the Cisco Thin Client model with the management software VXC. If you have then you are probably more then familiar with the incredibly clunky interface, the numerous work arounds, and …
Windows 10 is here and for most admins this means frustration and challenges getting that first working Windows 10 image. As in my previous sysprep articles, I've put together a simple help guide to get you through this process. The aim is to achiev…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question