All Forums >> [Scripting] >> WSH & Client Side VBScript >> Write something at a specific place in a text file Do you like VisualBasicScript.com? Link to us and help spread the word about our forum. Thanks!
Posts: 32
Score: 0
Joined: 5/13/2005
From: France
Status: offline
Hi, I am trying to edit a text file to find a specific expression (with regular expression) = expression to replace(A). Then, if the expression is find i replace it and if it's not find i m writting in a new line (no overwritte) my expression ( = my new expression (B)). The problem is that I don't want to write at the end of my file (not Appending) but after a specific line : example : php.ini
You can read the text file as one string. Example :
Function ReadFile ' Read whole file conLog as one string (max. possible length about 2 biljoen characters) Dim objFile, ts Set objFile = objFSO.GetFile(conLog) If objFile.Size > 0 Then Set ts = objFSO.OpenTextFile(conLog, conForReading) ReadFile = ts.ReadAll ts.Close End If End Function
Then you can process the string ReadFile as needed.
Good luck !
< Message edited by didorno -- 7/20/2005 6:16:03 AM >
Posts: 32
Score: 0
Joined: 5/13/2005
From: France
Status: offline
My problem isn't to read my file as a string but with this : i have to find [PHP] and replace the next line; Do you think (for the example) that my pattern should be : regexp.pattern = "[PHP]" &VbCrLf &"A" &VbCrLf and the replace string : "[PHP]" &VbCrLf &"B" &VbCrLf But if there is not B at the next line...
littlebouda, this works for me for your example. In writesomething.txt :
[PHP] A Z O ... ... [PHP] Z O ...
The vbscript file, running with cscript.exe :
conLog = "writesomething.txt" conForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.GetFile(conLog) If objFile.Size > 0 Then Set ts = objFSO.OpenTextFile(conLog, conForReading) ReadFile= ts.ReadAll ts.Close End If
WScript.Echo ReadFile
set oRE = New RegExp oRE.Global = True oRE.Pattern = "\[PHP\]" & "(\r\nA)?" WScript.Echo oRE.Replace(ReadFile, "[PHP]" & vbCrLf & "B")
Then you obtain your desired result. If you write the string to your file you are done. Good luck.
< Message edited by didorno -- 7/20/2005 6:17:09 AM >
The next piece of code writes the whole new string to a file conLog. Add it to the given code.
TekstIn = oRE.Replace(ReadFile, "[PHP]" & vbCrLf & "B") conLog = "Your new file name" OpenTextFileTest(TekstIn)
Sub OpenTextFileTest(TekstIn) ' Write text in logfile : conLog, if file not exist, make it Dim f conForWriting = 2 conCreateFile = True Set f = objFSO.OpenTextFile(conLog, conForWriting, conCreateFile) f.Write TekstIn f.Close End Sub
(I have not tested the above part.)
Good luck.
< Message edited by didorno -- 7/20/2005 6:17:57 AM >