Put new text on the same line in the output file - vbscript

I'm trying to make a settings file for my. Vbs happens that it also creates settings for my. Bat file and add new text to invest the same place the text on the same line the file creates a new line.
Ex:
CBNC-Blacklist =TEST
When I add a new text with the old it is well
CBNC-Blacklist =TEST
SDSADADA
Sub Main()
Dim Blist
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("A\a00_Blacklist.ini")
If objFile.Size > 0 Then
Set objReadFile = objFSO.OpenTextFile("A\a00_Blacklist.ini", 1)
strContents = objReadFile.ReadAll
objReadFile.Close
End if
Set WshShell = CreateObject("WScript.Shell")
Const ForReading = 1, ForWriting = 2, ForAppending = 8, CreateIfNeeded = True
Blist = Inputbox(vbcrlf & "Digite abaixo os itens que você deseja adicionar" & vbcrlf & "na Blacklist separando os mesmos com espaços:", "NoCheating", strContents)
If Blist = "" Then
msgbox "A Blacklist NÃO foi alterada!",vbExclamation,"NoCheating"
Else
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objMiFichero = objFSO.OpenTextFile("A\a00_Blacklist.ini", ForWriting, CreateIfNeeded)
objMiFichero.WriteLine( Blist )
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objMiFichero = objFSO.OpenTextFile("A\a00_Config_2.ini", ForWriting, CreateIfNeeded)
objMiFichero.WriteLine( "CBNC-Blacklist="&Blist )
msgbox "A Blacklist foi atualizada!",vbInformation,"NoCheating"
End if
End Sub
On Error Resume Next
Main
If Err.Number Then
WScript.Quit 4711
End If

Unfortunately, VBScript doesn't have a "seek" statement to position a file pointer. And you can't combine any of the file modes (ForReading, ForWriting, ForAppending) so that prevents you from "reading" the file until you get to a certain position and then writing at that position. (I've always wondered why they chose bit-position values (1, 2, 8) when you can't combine the values anyway. They could have just used 1, 2, 3).
What you can do, however, is parse your original ini file and write to a new one. If nothing should change, just write the original line to the new file. If the value should change, write a new value to your new file. For example, if you wanted to change the value of CBNC-Blacklist from TEST to NEW:
Set FileIn = objFSO.OpenTextFile("c:\settings.ini", ForReading)
Set FileOut = objFSO.CreateTextFile("c:\settings-new.ini", True)
Do Until FileIn.AtEndOfStream
' Read a line from the original file...
strLine = FileIn.ReadLine()
' Is this the line we want to change?
If Left(strLine, 15) = "CBNC-Blacklist=" Then
' Write the new value to the new file.
FileOut.WriteLine "CBNC-Blacklist=NEW"
Else
' Just write the original line to the new file.
FileOut.WriteLine strLine
End If
Loop
FileIn.Close
FileOut.Close
' Finally, replace the original settings file with the new one...
objFSO.CopyFile "c:\settings-new.ini", "c:\settings.ini", True
Of course you could make this more modular by creating a subroutine that accepts the "key" and "value" as parameters. I just wanted to keep things simple for this example.

I got what I wanted and I have to say it was very difficult anyway thanks for the help and the code below is the code ... I could always read the first line. Ini file and always writes in the first well.
Sub Main()
Dim Blist
Const ForReading = 1, ForWriting = 2, ForAppending = 8, CreateIfNeeded = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("A\a00_Blacklist.ini", ForReading)
For i = 4 to 3
objTextFile.ReadLine
Next
strLine = objTextFile.ReadLine
Set WshShell = CreateObject("WScript.Shell")
Blist = Inputbox(vbcrlf & "Digite abaixo os itens que você deseja adicionar" & vbcrlf & "na Blacklist separando os mesmos com espaços:","NoCheating",strLine)
If Blist = "" Then
msgbox "A Blacklist NÃO foi alterada!",vbExclamation,"NoCheating"
Else
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objMiFichero = objFSO.OpenTextFile("A\a00_Blacklist.ini", ForWriting, CreateIfNeeded)
objMiFichero.WriteLine( Blist )
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objMiFichero = objFSO.OpenTextFile("A\a00_Config_2.ini", ForWriting, CreateIfNeeded)
objMiFichero.WriteLine( "CBNC-Blacklist="&Blist )
msgbox "A Blacklist foi atualizada!",vbInformation,"NoCheating"
End if
End Sub
On Error Resume Next
Main
If Err.Number Then
WScript.Quit 4711
End If

Related

variable isnt updating as the code loops through

Ive written some code that loops through text files in a folder and updates them with an addiotnal header "TREATMENT_CODE" and then appends a code to the end of each line within each text file. The code is taken from the txt file name. Ive set this as a variable called TCode. The problem Im having is that the TCode variable isn't changing after the first loop through. Can anybody help? Thanks
Please excuse all of the msgbox lines, just me using them to figure out whats going on.
Code:
Option Explicit
Dim FSO, FLD, FIL, TS
Dim strFolder, strContent, strPath, FileName, PosA, TCode, rfile, Temp, dataToAppend, fulldata, wfile, TempArr, i
Const ForReading = 1, ForWriting = 2, ForAppending = 8
'Change as needed - this names a folder at the same location as this script
strFolder = "C:\Users\User1\OneDrive - Company/Documents\Temporary_delete_every_month\CRM_combiner_macro\Looping_test\files to amend"
'Create the filesystem object
Set FSO = CreateObject("Scripting.FileSystemObject")
'Get a reference to the folder you want to search
set FLD = FSO.GetFolder(strFolder)
'loop through the folder and get the file names
For Each Fil In FLD.Files
'MsgBox Fil.Path
'If UCase(FSO.GetExtensionName(Fil.Name)) = ".txt" Then
strPath = Fil.Path
'msgbox strPath
'strPath = Replace(strPath,"""","")
'msgbox strPath
posA = InStrRev(strPath, "\") +1
TCode = "|" & Mid(strPath, posA, 11)
msgbox "this is TCode " & TCode
Set fso = CreateObject("scripting.filesystemobject")
'msgbox "next file to amend" & strPath
Set rfile = fso.OpenTextFile(strPath, ForReading) 'File opened in Read-only mode
While Not rfile.AtEndOfStream
temp=rfile.ReadLine()
If rfile.Line=2 Then
dataToAppend = "|TREATMENTCODE"
ElseIf rfile.Line=3 Then
dataToAppend = TCode
End If
fulldata = fulldata & temp & dataToAppend & "|||"
Wend
rfile.Close
fulldata = Left(fulldata,Len(fulldata)-2)
Set wfile = fso.OpenTextFile(strPath, ForWriting) 'File opened in write mode
tempArr = Split(fulldata,"|||")
For i=0 To UBound(tempArr)
wfile.WriteLine tempArr(i)
Next
wfile.Close
Set fso= Nothing
'End If
'Clean up
Set TS = Nothing
Set FLD = Nothing
Set FSO = Nothing
set rfile = Nothing
set wfile = Nothing
set tempArr = Nothing
set Temp = Nothing
set TCode = Nothing
Next
MsgBox "Done!"

VBscript Replace text with part of filename

I have a directory of files that I want to Loop through and use part of their filename to replace text in a template doc.
For example one filename may be 'NV_AD32_city.dxf'. All files in the directory follow the same filename pattern of XX_XXXX_string.dxf, using two underscores.
I need to capture the string to the right of the first "_" and to the left of the "."so for this example that would be 'AD32_city'
How do I script to use capture that text of the active file to replace text in the template? I guess I need to create an object? But what is the object to use for the current file from a directory?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Thx for the replies, guys. After several days of trying your code I am just not "getting it". I understand it is set up to take the part of the filename's string that I want but how do I tell the script to use the current file I am looping through? Here is my script so far. I have your code on line 20 under the Sub 'GetNewInputs'
Set fso = CreateObject("Scripting.FileSystemObject")
Option Explicit
Dim WritePath : WritePath = "S:\TempFolder\"
Dim OutFile : OutFile = "VEG_DXF-2-SHP_script-"
Dim WorkingFile : WorkingFile = GetFileContent(SelectFile())
Dim NewState, NewSection, NewArea
Dim OldState, OldSection, OldArea
Call GetNewInputs()
Call GetOldInputs()
Sub GetNewInputs()
NewState = UCase(InputBox("INPUT STATE:", _
"INPUT STATE", "SOCAL"))
NewSection = ("Section_" & InputBox("INPUT SECTION NUMBER:", _
"INPUT SECTION", "14"))
NewArea = "^[^_]+_(.*)\.dxf$"
End Sub
Private Sub GetOldInputs()
OldState = "XX"
OldSection = "_X"
OldArea = "ZZZZ"
End Sub
Function SelectFile()
SelectFile = vbNullString
Dim objShell : Set objShell = WScript.CreateObject("WScript.Shell")
Dim strMSHTA : strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
&"<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
&".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
SelectFile = objShell.Exec(strMSHTA).StdOut.ReadLine()
If SelectFile = vbNullString Then
WScript.Echo "No file selected or not a text file."
WScript.Quit
End If
End Function
Private Function GetFileContent(filePath)
Dim objFS, objFile, objTS
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.GetFile(filePath)
Set objTS = objFile.OpenAsTextStream(1, 0)
GetFileContent = objTS.Read(objFile.Size)
Set objTS = Nothing
End Function
For Each FileRefIn fso.GetFolder("S:\SOCAL\Section_14\Veg DXFs\").Files
NewFile = WorkingFile
NewFile = Replace(NewFile, OldState, NewState)
NewFile = Replace(NewFile, OldSection, NewSection)
NewFile = Replace(NewFile, OldArea, NewArea)
WriteFile NewFile, WritePath & OutFile & ".gms"
WScript.Echo NewArea
Next
Private Sub WriteFile(strLine,fileName)
On Error Resume Next
Dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Do Until IsObject(objFile)
Set objFile = objFSO.OpenTextFile(fileName, 8, True)
Loop
objFile.WriteLine strLine
objFile.Close
End Sub
Well, that’s actually two questions.
To enumerate files in a directory, you can use FileSystemObject, like this (untested)
const strFolderPath = "C:\Temp\Whatever"
set objFSO = CreateObject( "Scripting.FileSystemObject" )
set objFolder = objFSO.GetFolder( strFolderPath )
set colFiles = objFolder.Files
for each objFile in colFiles
' Do whatever you want with objFile
next
Here's the reference of those objects properties/methods.
And to extract portion of file names, you could use a regular expression.
Here’s some guide how to use'em in VBScript.
The following expression should work for you, it will capture the portion of that file names you asked for:
"^[^_]+_(.*)\.dxf$"
If you need to edit the content of the .dxf files, you will need to work within the AutoCAD VBA (Visual Basic for Applications) environment.
If that is the case, you will need to start with something like below:
GetObject("AutoCAD.Application.20")
CreateObject("AutoCAD.Application.20")
https://knowledge.autodesk.com/search-result/caas/CloudHelp/cloudhelp/2015/ENU/AutoCAD-ActiveX/files/GUID-0225808C-8C91-407B-990C-15AB966FFFA8-htm.html
** Please take note that "VBA is no longer distributed with the AutoCAD installation; it must be downloaded and installed separately. The VBA Enabler for Autodesk AutoCAD can be downloaded here."

How to correct VBscript runtime error: input past end of file

I'm getting the following error for this code. Please could you advise where it is wrong? Line 71 is "urls2 = objInputFile.ReadAll".
Line 71
Character 1
Error: Input past end of file
Code: 800A003E
Source: Microsoft VBScript runtime error.
inputfile = "C:\Evernote.html"
outputfolder = "c:\"
msgbox("launched. press ok to continue")
'create urls1.txt
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set objOutputFile = objFileSystem.CreateTextFile(outputfolder & "urls1.txt", TRUE)
'read inputfile (evernote exported html)
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set objInputFile = objFileSystem.OpenTextFile(inputfile, 1)
html = objInputFile.ReadAll
objInputFile.Close
'split html var
html = Split(html, "<tr><td><b>Source:</b></td><td><a href=""")
'loop through html array and clean up the results so you get just the urls
'and write them to urls1.txt
For i = 1 To UBound(html)
checkA = InStr(html(i), """")
if checkA > 1 then
html(i) = Split(html(i), """")
urls = html(i)(0)
objOutputFile.WriteLine(urls)
end if
Next
'remove duplicates
'create urls2.txt
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set objOutputFile = objFileSystem.CreateTextFile(outputfolder & "urls2.txt", TRUE)
'read urls1.txt and remove duplicates and write results to urls2.txt
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = outputfolder & "urls1.txt"
Set objFile = objFS.OpenTextFile(strFile)
Set d = CreateObject("Scripting.Dictionary")
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If Not InStr(strLine,"--------") >0 Then
If Not d.Exists(strLine) Then
d.Add strLine , 0
End If
End If
Loop
x=d.Items
For Each strKey In d.keys
objOutputFile.WriteLine(strKey)
Next
'sort alphabetically
'read urls2.txt and sort everything alphabetically
'read urls2.txt
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set objInputFile = objFileSystem.OpenTextFile(outputfolder & "urls2.txt", 1)
urls2 = objInputFile.ReadAll
objInputFile.Close
'split each line into array
urls2 = Split(urls2, VBCrLf)
'sort urls2 array by alphabet with bubble sort method
For i = (UBound(urls2) - 1) to 0 Step -1
For j= 0 to i
If UCase(urls2(j)) > UCase(urls2(j+1)) Then
strHolder = urls2(j+1)
urls2(j+1) = urls2(j)
urls2(j) = strHolder
End If
Next
Next
'write the sorted version of urls2.txt in urlsfinal.txt
'create urlsfinal.txt
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set objOutputFile = objFileSystem.CreateTextFile(outputfolder & "urlsfinal.txt", TRUE)
'write all sorted vars from urls2 array to urlsfinal.txt
For i = 0 to UBound(urls2)
objOutputFile.WriteLine(urls2(i))
next
msgbox("all done")
The problem is your source file urls2.txt is empty. The reason for this is you are not closing your files after you write to them. You need to add this after you have finished writing out to urls1.txt and urls2.txt.
objOutputFile.Close
Also, you don't need to continually recreate the instance of objFileSystem every time you access the files. You can instantiate it once at the top.
Be sure to be a good memory citizen and destroy all objects you set in your code.
Set objFileSystem = Nothing

vbscript search string in multiple files

Please advice how changes the current single incoming log file to search multiple files.
Dim strTextToFind, strInputFile, strOutputFile, boolMatchCaseSensitive
Dim objFSO, objInputFile, strFoundText, strLine, objOutputFile
strTextToFind = Inputbox("Enter the text you would like to search for.")
strInputFile = "C:\Users\mmmanima\Desktop\mani\Day_16.txt"
iF YOU CAN NOTICED, IM ONLY ACCESS THE day_16 FILE
strOutputFile = "C:\Users\mmmanima\Desktop\texting As\result.txt"
Set objFSO = CreateObject("Scripting.FilesystemObject")
Const intForReading = 1
Const intForWriting = 2
Const intForAppending = 8
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)
Do until objInputFile.atEndOfStream
strLine = objInputFile.ReadLine
If InStr(strLine,strTextToFind) > 0 Then
strFoundText = strLine
If strFoundText <> "" Then
Set objOutputFile = objFSO.OpenTextFile(strOutputFile,intForAppending, True)
objOutputFile.WriteLine strFoundText
objOutputFile.Close
Set objOutputFile = Nothing
End If
End If
loop
objInputFile.Close
Set objInputFile = Nothing
WScript.Quit
VBScript required to search userinput string into the share folder and there is 60 files.
As I believe you want to search through the all files in a particular folder. Then I suggest you to loop you action while all files are read
to do that it's easier to maintain sub or function
pseudo:
var inputFolder = ".\myfolder"
foreach file in the inputFolder
{
inputFile = file
searchIn(inputFile)
}
sub searchIn(inputFile)
{
'do your current works here
}
code:
This part will give you the all file names
Set fso = CreateObject("Scripting.FileSystemObject")
inputFldr = Replace(wscript.scriptfullname,wscript.scriptname,".\")
Set fldr = fso.getFolder(inputFldr)
For Each file In fldr.Files
'call to your function
Next
----------plese aware of typos------
Dim strTextToFind, strInputFile, strOutputFile, boolMatchCaseSensitive
Dim objFSO, objInputFile, strFoundText, strLine, objOutputFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
inputFldr = Replace(wscript.scriptfullname,wscript.scriptname,".\")
Set fldr = objFSO.getFolder(inputFldr)
strTextToFind = Inputbox("Enter the text you would like to search for.")
For Each file In fldr.Files
yourFunctionName(file )
Next
sub yourFunctionName(inputFile)
strInputFile = inputFile
strOutputFile = ".\result.txt"
Const intForReading = 1
Const intForWriting = 2
Const intForAppending = 8
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)
Do until objInputFile.atEndOfStream
strLine = objInputFile.ReadLine
If InStr(strLine,strTextToFind) > 0 Then
strFoundText = strLine
If strFoundText <> "" Then
Set objOutputFile = objFSO.OpenTextFile(strOutputFile,intForAppending, True)
objOutputFile.WriteLine strFoundText
objOutputFile.Close
Set objOutputFile = Nothing
End If
End If
loop
objInputFile.Close
Set objInputFile = Nothing
end sub
WScript.echo "done"
WScript.Quit
You can try this vbscript, i added a function BrowseForFolder()
Option Explicit
Dim strTextToFind,inputFldr,strInputFile,strOutputFile,path,fldr
Dim objFSO, objInputFile,strFoundText,strLine,objOutputFile,file,ws
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("wscript.Shell")
path = objFSO.GetParentFolderName(wscript.ScriptFullName)
strOutputFile = path & "\result.txt"
If objFSO.FileExists(strOutputFile) Then
objFSO.DeleteFile(strOutputFile)
End if
inputFldr = BrowseForFolder()
Set fldr = objFSO.getFolder(inputFldr)
strTextToFind = Inputbox("Enter the text you would like to search for it !","Enter the text you would like to search for it !","wscript")
For Each file In fldr.Files
Call Search(file,strTextToFind)
Next
ws.run strOutputFile
'***************************************************************************************************************
Sub Search(inputFile,strTextToFind)
strInputFile = inputFile
Const intForReading = 1
Const intForWriting = 2
Const intForAppending = 8
Set objInputFile = objFSO.OpenTextFile(strInputFile,intForReading, False)
Do until objInputFile.atEndOfStream
strLine = objInputFile.ReadLine
If InStr(strLine,strTextToFind) > 0 Then
strFoundText = strLine
If strFoundText <> "" Then
Set objOutputFile = objFSO.OpenTextFile(strOutputFile,intForAppending, True)
objOutputFile.WriteLine "The Path of file ===> "& DblQuote(strInputFile) & VbCRLF &_
"String found "& DblQuote(strTextToFind) & " ===> "& DblQuote(strFoundText) & VbCRLF & String(100,"*")
objOutputFile.Close
Set objOutputFile = Nothing
End If
End If
loop
objInputFile.Close
Set objInputFile = Nothing
End sub
'***************************************************************************************************************
Function BrowseForFolder()
Dim ws,objFolder,Copyright
Set ws = CreateObject("Shell.Application")
Set objFolder = ws.BrowseForFolder(0,"Choose the folder to search on it ",1,"c:\Programs")
If objFolder Is Nothing Then
Wscript.Quit
End If
BrowseForFolder = objFolder.self.path
end Function
'****************************************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*****************************************************
A bit late in the day after such a long time gap to address Mara Raj's problem with Hackoo's script but here it is for any others who may be interested. On starting the script it automatically deletes any existing result.txt file. Should the script subsequently go on to find "no match" it fails to generate a results.txt file as it would normally do if there were a match. The simplest way to correct this is to insert:
If objFSO.FileExists(strOutputFile) Then
else
wscript.echo "No Matches Found"
wscript.Quit
end if
between "next" and "ws.run strOutputFile"

Year check, update in text file using VBS

Want to check if year is actual year in text file and update if not actual, 2013.
For example text line is: SET YEAR=2012
So far I have only been able to write actual year into file, but now I need to update the information in file if it exist...
Appreciating any help here.
dim filesys
Set filesys = CreateObject("Scripting.FileSystemObject")
path = filesys.GetAbsolutePathName("C:\Backups\Machine.bat")
getname = filesys.GetFileName(path)
If filesys.FileExists(path) Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set filesys = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFile("C:\Backups\Machine.bat")
Set objFile = objFSO.OpenTextFile("C:\Backups\Machine.bat", 8)
objFile.WriteLine
objFile.Write("SET YEAR=")
objFile.WriteLine(Year(Date()))
objFile.Close
End if
You can replace a particular line in a text file like this:
path = "C:\Backups\Machine.bat"
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(path) Then
Set inFile = fso.OpenTextFile(path)
Set outFile = fso.OpenTextFile(path & ".tmp", 2, True)
Do Until inFile.AtEndOfStream
line = inFile.ReadLine
If UCase(Left(Trim(line), 9)) = "SET YEAR=" Then
outFile.WriteLine "SET YEAR=" & Year(Date)
Else
outFile.WriteLine line
End If
Loop
inFile.Close
outFile.Close
fso.DeleteFile path, True
fso.MoveFile path & ".tmp", path
End If

Resources