Read a file's data within a specified range using VB script. Is it possible? - vbscript

This is the middle of the code I'm trying to work with. Is there a way to make the file it's reading open and read from line 2 to line 97? Where I need the correction is starred (****). What I'm trying to do is get the data from lines 2 through 97 to compare to another file I'll have to open from the same lines. The beginning and ends of each file are different but the middle information should match thus I need these specific lines.
' Build Aliquot file name
strFile = aBarcodeExportDir & "A-" & yearStr & "-" & splitStr2(0) & ".csv"
'msgbox("open file: " & strFile)
If (objFS.FileExists(strFile)) Then
' Open A file
Set objFile = objFS.OpenTextFile(strFile)
' Build string with file name minus extension - used later to determine EOF
strFileNameNoExtension = "A-" & yearStr & "-" & splitStr2(0)
' Create dictionary to hold key/value pairs - key = position; value = barcode
Set dictA = CreateObject("Scripting.Dictionary")
' Begin processing A file
Do Until objFile.AtEndOfStream(*****)
' Read a line
strLine = objFile.ReadLine(*****)
' Split on semi-colons
splitStr = Split(strLine, ";")
' If splitStr array contains more than 1 element then continue
If(UBound(splitStr) > 0) Then
' If barcode field is equal to file name then EOF
If(splitStr(6) = strFileNameNoExtension) Then
' End of file - exit loop
Exit Do
Else
' Add to dictionary
' To calculate position
' A = element(2) = position in row (1-16)
compA = splitStr(2)
' B = element(4) = row
compB = splitStr(4)
' C = element(5.1) = number of max positions in row
splitElement5 = Split(splitStr(5), "/")
compC = splitElement5(0)
' position = C * (B - 1) + A
position = compC * (compB - 1) + compA
barcode = splitStr(6) & ";" & splitStr(0) & ";" & splitStr(1) & ";" & splitStr(2)
'msgbox(position & ":" & barcode)
' Add to dictionary
dictA.Add CStr(position), barcode
End If
End If
Loop
' Close A file
objFile.Close

To give the exact answer, we may have to look at your text files(I mean with all the split functions you are using). But, If you just want to compare lines 2-97 of two text files, you can get a hint from the following piece of code:
strPath1 = "C:\Users\gr.singh\Desktop\abc\file1.txt" 'Replace with your File1 Path
strPath2 = "C:\Users\gr.singh\Desktop\abc\file2.txt" 'Replace with your File2 Path
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile1 = objFso.OpenTextFile(strPath1,1)
Set objFile2 = objFso.OpenTextFile(strPath2,1)
blnMatchFailed = False
Do Until objFile1.AtEndOfStream
If objFile1.Line=1 Then
objFile1.SkipLine() 'Skips the 1st line of both the files
objFile2.SkipLine()
ElseIf objFile1.Line>=2 And objFile1.Line<=97 Then
strFile1 = objFile1.ReadLine()
strFile2 = objFile2.ReadLine()
If StrComp(strFile1,strFile2,1)<>0 Then 'textual comparison. Change 1 to 0, if you want binary comparison of both lines
blnMatchFailed = True
intFailedLine = objFile1.Line
Exit Do 'As soon as match fails, exit the Do while Loop
Else
blnMatchFailed = False
End If
Else
Exit Do
End If
Loop
If blnMatchFailed Then
MsgBox "Comparison Failed at line "&intFailedLine
Else
MsgBox "Comparison Passed"
End If
objFile1.Close
objFile2.Close
Set objFile1 = Nothing
Set objFile2 = Nothing
Set objFso = Nothing

Related

vbScript read file from an specific line

Hello everyone I got a doubt, about how to read a .txt file starting in specific line, I got the line number from I want to start to read, and I'm trying to read it, but always start from the first line
And it takes a several minutes to reach my needed line
Here's my code
'Call F_CMN_GRL_FindObjects(17,15)
strProperty = F_CMN_GRL_GlobalMain(6,17,15,0,"all items" )
strLine = split(strProperty,",")
Print strLine(0)
strValor = split(strLine(0)," ")
Print strValue(1)
numberLine = strValue(1)
Call readFromLine(numberLine)
Function readFromLine(numberLine)
numberLineEnd =numberLine + 7
print numberLine
print numberLineEnd
' Option Explicit
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oFile : Set oFile = oFso.OpenTextFile("C:\myFile.txt", 1)
' Dim myArray()
' ReDim myArray(0)
'numberLine it's the number line from I want to start to read and I want to read until numberLineEnd
For i = numberLine to numberLineEnd step 1
strLine = oFile.ReadLine
print strLine
Next
'i = i + 1
'numberLine = numberLine + 1
End Function
I've solved it by doing it like this:
Dim i
Do While (i <= numeroLineaFin)
If (i => numeroLinea) and (i<=numeroLineaFin) Then
' If i <= numeroLineaFin Then
' tmpstr = tmpstr & oFile.readline & VbCrLf
tmpstr = oFile.readline
print tmpstr
' else
' oFile.SkipLine
' End If
else
oFile.SkipLine
end if
i = i + 1
Loop

I want to search for the particular word and then after that word on each line i want to add ; in the start

Using below code I was able to add ; in the start of each line but the I want to add ; after a particular word is found e.g. [Abc]. How to do this using VBScript?
Const ForReading=1
Const ForWriting=2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set f = objFSO.OpenTextFile("D:\sam.txt", ForReading)
Do Until f.AtEndOfStream
strText = f.ReadLine
If Len(strText) = 0 Then
blnFound = True
MsgBox "blank line found"
strText = vbNewLine & strText
strContents = strContents & strText & vbCrlf
Else
strText = ";" & strText
strContents = strContents & strText & vbCrlf
End If
Loop
f.Close
Set f = objFSO.OpenTextFile("D:\sam.txt", Forwriting)
f.WriteLine strContents
f.Close
Sam.txt is containing some lines, e.g.
Hi, need help
This is a sample text file
[Abc]
How are you
Hope you are doing well!
So I want the output sam.txt file should have below data inside it:
Hi, need help
This is a sample text file
[Abc]
;How are you
;Hope you are doing well!
So, basically, you have an INI-style file and want the entries in a particular section commented. That can be achieved like this:
filename = "D:\sam.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
txt = Split(fso.OpenTextFile(filename).ReadAll, vbNewLine)
disable = False
For i = 0 To UBound(txt)
If Left(txt(i), 1) = "[" Then
If txt(i) = "[Abc]" Then
disable = True
Else
disable = False
End If
End If
If disable Then txt(i) = ";" & txt(i)
Next
fso.OpenTextFile(filename, 2).Write Join(txt, vbNewLine)
Try this
Option Explicit
Dim FSO ' Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim ReadTxtFile, WriteTxtFile ' Object
Dim TextLine, TextLineToWrite ' String
Dim AddStr' bool
' Open both text file in the same time
Set ReadTextFile = FSO.OpenTextFile("Sam.txt", 1) ' Open file to read
Set WriteTextFile = FSO.OpenTextFile("Sam_new.txt", 2, True) ' Open file to write
' Do read file as normal but add a switch
' Write original text line to text file while switch is disabled
' Add str to the text line and write once switch is trigger
AddStr = False ' Add str disabled
Do Until ReadTextFile.AtEndOfStream ' Start Read
Textline = ReadTextFile.Readline
If AddStr = True Then ' If add str enabled
TextLineToWrite = ";" & Textline ' Add string
Else ' if add str disabled
TextLineToWrite = Textline ' write original line
End If
If Trim(Textline) = "[ABC]" Then ' If indicator read
AddStr = True ' add str write
End if
WriteTextFile.WriteLine TextLineToWrite ' Write file when each line is read
Loop
ReadTextFile.Close
WriteTextFile.Close
msgbox "Done"

VBScript Create puzzle by splitting document into multiple documents that cannot be read separately

For a scavenger hunt I wanted to give my nephews 4 parts of the same letter that they would have to combine to read. I couldn't find anything online to use quickly, so I wrote one. I will updated with better code if you have some ideas.
'****************** Change things here ****************
'Change the number in perenthesis to set the number of files
Dim Letters(4)
'Set the original filename here:
originalFile = "Letter.txt"
'Set a letter to use as a syncronizer in addition to punctuation and line breaks
charSync = asc("o")
'*********************************************************
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(originalFile , 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
Randomize
selLetter = Int((Ubound(Letters))*Rnd+1)
If (asc(strCharacters) < 46) or (asc(strCharacters) = charSync) then
for i = 1 to Ubound(Letters)
Letters(i) = Letters(i) & strCharacters
next
else
for i = 1 to Ubound(Letters)
if i = selLetter then
Letters(i) = Letters(i) & strCharacters
else
Letters(i) = Letters(i) & " "
end if
next
end if
Loop
For n = 1 to Ubound(Letters)
outFileName = replace(originalFile ,".",n & ".")
Set objFile = objFSO.CreateTextFile(outFileName,True)
objFile.Write Letters(n)
objFile.Close
next
Set objFSO=Nothing
Usage:
Create a text file you want to split up randomly
Edit the script for the following:
Set the number of documents to split it into
Set the file name of the file to update
Select a synch character if you want to
Run the script and it will create numbered files
Use equal character spacing font like system to read by holding up to light
'****************** Change things here ****************
'Change the number in perenthesis to set the number of files
Dim Letters(4)
'Set the original filename here:
originalFile = "Letter.txt"
'Set a letter to use as a syncronizer in addition to punctuation and line breaks
charSync = asc("o")
'*********************************************************
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(originalFile , 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
'uncomment next 2 comments to simplify and change only once per word:
'If strCharacters = " " then
Randomize
selLetter = Int((Ubound(Letters))*Rnd+1)
'end if
If (asc(strCharacters) < 46) or (asc(strCharacters) = charSync) then
for i = 1 to Ubound(Letters)
Letters(i) = Letters(i) & strCharacters
next
else
for i = 1 to Ubound(Letters)
if i = selLetter then
Letters(i) = Letters(i) & strCharacters
else
Letters(i) = Letters(i) & " "
end if
next
end if
Loop
For n = 1 to Ubound(Letters)
outFileName = replace(originalFile ,".",n & ".")
Set objFile = objFSO.CreateTextFile(outFileName,True)
objFile.Write Letters(n)
objFile.Close
next
Set objFSO=Nothing
Usage:
Create a text file you want to split up randomly
Edit the script for the following:
Set the number of documents to split it into
Set the file name of the file to update
Select a synch character if you want to
Run the script and it will create numbered files
Use equal character spacing font like system to read by holding up to light

vbs using .Read ( ) with a variable not an interger

I have a problem in that I need to read a specified quantity of characters from a text file, but the specified quantity varies so I cannot use a constant EG:
variable = WhateverIsSpecified
strText = objFile.Read (variable) ' 1 ~ n+1
objOutfile.write strText
NOT
strText = objFile.Read (n) ' n = any constant (interger)
When using the first way, the output is blank (no characters in the output file)
Thanks in advance
UPDATE
These are the main snippets in a bit longer code
Set file1 = fso.OpenTextFile(file)
Do Until file1.AtEndOfStream
line = file1.ReadLine
If (Instr(line,"/_N_") =1) then
line0 = replace(line, "/", "%")
filename = file1.Readline
filename = Left(filename, len(filename)-3) & "arc"
Set objOutFile = fso.CreateTextFile(destfolder & "\" & filename)
For i = 1 to 5
line = file1.Readline
next
nBytes = line 'this line contains the quantity needed to be read eg 1234
Do until Instr(line,"\") > 0
line = file1.ReadLine
Loop
StrData = ObjFile.Read (nBytes)
objOutFile.Write StrData
objOutFile.close
End if
Loop
WScript.quit
My own stupid error,
StrData = ObjFile.Read (nBytes)
should be
StrData = file1.Read (nBytes)

Script won't split line at "=" Delimeter

The script below works in finding duplicates.
But most of the files i'm reading follow this format:
ServerName(1) = "Example1"
ServerName(2) = "Example1"
ServerName(3) = "Example3"
ServerName(4) = "Example4"
ServerName(5) = "Example5"
The 'cut' variable in the code below is supposed to cut the string at the "=" delimiter and return the value that comes after the "=" delimeter.
It should write to the duplicate file "Example1" but instead writes nothing. How would I make it so that the script below reads a file and only finds the duplicate in values after the "=" delimeter.
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
FileName = "Test.txt"
PathToSave = "C:"
Path = (PathToSave & FileName)
Set objFile = objFSO.OpenTextFile(Path, ForReading)
Set objOutputFile = objFSO.OpenTextFile(PathToSave & "Noduplicates.txt", 2, True)
Set objOutputFile2 = objFSO.OpenTextFile(PathToSave & "Duplicates.txt", 2, True)
objOutputFile.WriteLine ("This document contains the " & path & " file without duplicates" & vbcrlf)
objOutputFile2.WriteLine ("This document contains the duplicates found. Each line listed below had a duplicate in " & Path & vbcrlf)
Dim DuplicateCount
DuplicateCount = 0
Set Dict = CreateObject("Scripting.Dictionary")
Do until objFile.atEndOfStream
strCurrentLine = LCase(Trim(objFile.ReadLine))
Cut = Split(strCurrentline,"=")
If not Dict.Exists(LCase(Trim(cut(strCurrentLine)))) then
objOutputFile.WriteLine strCurrentLine
Dict.Add strCurrentLine,strCurrentLine
Else Dict.Exists(LCase(Trim(cut(strCurrentLine))))
objOutputFile2.WriteLine strCurrentLine
DuplicateCount = DuplicateCount + 1
End if
Loop
If DuplicateCount > 0 then
wscript.echo ("Number of Duplicates Found: " & DuplicateCount)
Else
wscript.echo "No Duplicates found"
End if
Cut is your array, so Cut(1) is the portion after the =. So that's what you should test for in your dictionary.
If InStr(strCurrentline, "=") > 0 Then
Cut = Split(strCurrentline,"=")
If Not Dict.Exists(Cut(1)) then
objOutputFile.WriteLine strCurrentLine
Dict.Add Cut(1), Cut(1)
Else
objOutputFile2.WriteLine strCurrentLine
DuplicateCount = DuplicateCount + 1
End if
End If
I makes no sense at all to ask Split to return an array with one element by setting the 3rd parameter to 1, as in
Cut = Split(strCurrentline,"=",1)
Evidence:
>> WScript.Echo Join(Split("a=b", "=", 1), "*")
>>
a=b
>> WScript.Echo Join(Split("a=b", "="), "*")
>>
a*b
BTW: ServerName(5) = "Example5" should be splitted on " = "; further thought about the quotes may be advisable.
Update wrt comments (and downvotes):
The semantics of the count parameter according to the docs:
count
Optional. Number of substrings to be returned; -1 indicates that all substrings are returned. If omitted, all substrings are returned.
Asking for one element (not an UBound!) results in one element containing the input.
Evidence wrt the type mismatch error:
>> cut = Split("a=b", "=", 1)
>> WScript.Echo cut
>>
Error Number: 13
Error Description: Type mismatch
>>
So please think twice.

Resources