Link to home
Start Free TrialLog in
Avatar of John_2000
John_2000

asked on

How to open a file, look for a line and replace/add text via a script?

How would you recemend that I could open a file (Test1.log) and search for a line of text then pass data to that line via a script?  I have attached the file and the line I would like to edit.  I would like to be able to pass 123456789 as the value between the "", then save it (ex "123456789" />)
Before
<add key="websvc.PAD.ip"                      value= "" />

After
<add key="websvc.PAD.ip"                      value= "123456789" />

Please help...
Test1.log
Avatar of Shift-3
Shift-3
Flag of United States of America image

Paste the script below into a text file with a .vbs extension.  Customize the value of the strFile variable with the location of the log file.  Running the script will replace any instances of the original string with the new one.


Const ForReading = 1
Const ForWriting = 2
Const TriStateUseDefault = -2
 
strFile = "c:\test1.log"
strOldString = "<add key=" & Chr(34) & "websvc.PAD.ip" & Chr(34) & "	    		value= " & Chr(34) & Chr(34) & " />"
strNewString = "<add key=" & Chr(34) & "websvc.PAD.ip" & Chr(34) & "	    		value= " & Chr(34) & "123456789" & Chr(34) & " />"
 
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(strFile, ForReading, False, TriStateUseDefault)
 
strText = objTextFile.ReadAll
strText = Replace(strText, strOldString, strNewString)
objTextFile.Close
 
Set objTextFile = objFSO.OpenTextFile(strFile, ForWriting)
 
objTextFile.Write strText
objTextFile.Close

Open in new window

Avatar of John_2000
John_2000

ASKER

That works great!  But one more thing.....If there was a value already between the quotes, it will not update.  Would it be easy adjust this code to reflect that?
ASKER CERTIFIED SOLUTION
Avatar of Shift-3
Shift-3
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Nice Job!