Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read every 20 lines from a text file using vbscript?

Tags:

vbscript

I have 180 lines in a text file and want to read every 20 lines (1-20, 21-40...)

Here is my current code:

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objTextFile = objFSO.OpenTextFile("C:\Bess_Automation\EditFiles\TSTVLD1.txt", ForReading)

'Reading the count of lines
objTextFile.ReadAll
strLinecount=objTextFile.Line
msgbox strLinecount

strnumoftimes=Round((strLinecount/20),0)
msgbox strnumoftimes
like image 323
Pushpendra Singh Avatar asked Oct 18 '22 05:10

Pushpendra Singh


1 Answers

Here's how I'd approach the problem. This code sets the number of lines to be read at a time initially then opens the file for reading and sets up an array. While we're not finished reading the file, we add a line from it to myArray.

When we hit a multiple of 20 lines read, we report that and do whatever we need to with those 20 lines (in my case, I've just echoed them to the screen, separated by semicolons).

Then we reset the array to be empty again and repeat until all the file has been read, then output the final batch of lines (as otherwise they'd be ignored since we only do anything with batches of 20 in the example).

Option Explicit

Const LINES_TO_READ = 20
Dim iLines, iTotalLines
Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oFile : Set oFile = oFso.OpenTextFile("C:\temp\mytextfile.txt", 1)
Dim myArray()
ReDim myArray(0)
iLines = 0
iTotalLines = 0
While Not oFile.AtEndOfStream
    myArray(UBound(myArray)) = oFile.ReadLine
    iLines = iLines + 1
    ReDim Preserve myArray(UBound(myArray)+1)
    If iLines Mod LINES_TO_READ = 0 Then
        WScript.Echo iLines & " read now."
        ' do anything you like with the elements of myArray here before we reset it to empty
        WScript.Echo Join(myArray, ";")
        ' reset array to be totally empty again
        ReDim myArray(0)
    End If
Wend
WScript.Echo "Final Lines: " & Join(myArray, ";")
WScript.Echo "Total lines in file: " & iLines
like image 114
Dave Avatar answered Oct 21 '22 06:10

Dave