Windows Vista Forums
Vista Forums Home Join Vista Forums Windows 7 Forum Vista Tutorials Tags
Welcome to Windows Vista Forums. Our forum is dedicated to helping you find solutions with any problems, errors or issues you are experiencing with Windows Vista. The Vista forum also covers news and updates and has an extensive Windows Vista tutorial section that covers a wide range of tips and tricks.

Go Back   Vista Forums > Misc Newsgroups > VB Script

Vista - How to read the LAST NON-BLANK line from a text file?

Reply
 
Old 03-15-2009   #1 (permalink)
Tony Bansten


 
 

How to read the LAST NON-BLANK line from a text file?

How can I read the last non-blank (=non whitespace) line from a text file?

Ok, the most primitive way would be to start reading from the beginning and then loop
through all the lines until the end.

But that is rather unconvenient and cumbersome.

Is there a smarter way?

Tony


My System SpecsSystem Spec
Old 03-15-2009   #2 (permalink)
Pegasus [MVP]


 
 

Re: How to read the LAST NON-BLANK line from a text file?


"Tony Bansten" <tonytony@xxxxxx> wrote in message
news:49bcbeab$0$31869$9b4e6d93@xxxxxx-online.net...
Quote:

> How can I read the last non-blank (=non whitespace) line from a text file?
>
> Ok, the most primitive way would be to start reading from the beginning
> and then loop
> through all the lines until the end.
>
> But that is rather unconvenient and cumbersome.
>
> Is there a smarter way?
>
> Tony
The element you're dealing with is a "line". It is therefore unavoidable
that you process lines, regardless of whether this is "incovenient" or not.
While it is possible with VB Script to read the whole file in one lump, you
must still break this lump into its elements. Here is one way to do it:
1. Read one line.
2. Memorise it.
3. Read the next line.
4. If it is not blank, memorise it.
5. Go back to Step 3.

Here is a variant:
1. Read the whole file into a single long string variable.
2. Split the string variable into an array of lines.
3. Starting at the end of the array, look for the first non-blank line.
Even here you must deal with lines.


My System SpecsSystem Spec
Old 03-15-2009   #3 (permalink)
gillardg


 
 

Re: How to read the LAST NON-BLANK line from a text file?

another primitive way is to use a textbox

MsgBox(TextBox1.Lines.Length)


"Tony Bansten" <tonytony@xxxxxx> a écrit dans le message de groupe de
discussion : 49bcbeab$0$31869$9b4e6d93@xxxxxx-online.net...
Quote:

> How can I read the last non-blank (=non whitespace) line from a text file?
>
> Ok, the most primitive way would be to start reading from the beginning
> and then loop
> through all the lines until the end.
>
> But that is rather unconvenient and cumbersome.
>
> Is there a smarter way?
>
> Tony
>
My System SpecsSystem Spec
Old 03-15-2009   #4 (permalink)
Cor Ligthert


 
 

RE: How to read the LAST NON-BLANK line from a text file?

Hi Tony,

What I probably would do is loop from the end of the textfile to the
beginning until the character is no whitespace.

Probably is that the most effective, I don't think that this will be choosen
by any method which is behind the scene.

Cor

"Tony Bansten" wrote:
Quote:

> How can I read the last non-blank (=non whitespace) line from a text file?
>
> Ok, the most primitive way would be to start reading from the beginning and then loop
> through all the lines until the end.
>
> But that is rather unconvenient and cumbersome.
>
> Is there a smarter way?
>
> Tony
>
>
My System SpecsSystem Spec
Old 03-15-2009   #5 (permalink)
Paul Randall


 
 

Re: How to read the LAST NON-BLANK line from a text file?


"Tony Bansten" <tonytony@xxxxxx> wrote in message
news:49bcbeab$0$31869$9b4e6d93@xxxxxx-online.net...
Quote:

> How can I read the last non-blank (=non whitespace) line from a text file?
>
> Ok, the most primitive way would be to start reading from the beginning
> and then loop
> through all the lines until the end.
>
> But that is rather unconvenient and cumbersome.
>
> Is there a smarter way?
>
> Tony
I think that there could be a smarter way if you had some information about
how the file is built. For example, if you know that the end of file will
never contain more than some number of bytes (or maybe characters) in those
ending lines that contain only white space. Suppose you set a variable
called maxwhitespace to this value. You could use the textstream skip
method to skip to (filesize - maxwhitespace), read the rest of the file into
a single string and use a regex to search it for lines containing
non-whitespace. The last match will contain that last line.

With no information about where the last line of interest might be, you are
stuck with reading the whole file.

-Paul Randall


My System SpecsSystem Spec
Old 03-15-2009   #6 (permalink)
Michel Posseth


 
 

Re: How to read the LAST NON-BLANK line from a text file?

The most primitive way is what the luxury coders can do and that is reading
the whole file split it and then loop in reverse order
however if you once processed files of gigagbytes in size then you
understand that this isn`t going to work in all situations your app will
blow up ( out of memory )
or it will become verry slow .

The following piece of code solves this problem as it only reads a peace of
the end of the file and then split the lines
so it doesn`t loop through a large file it reads a chunk at the end and then
splits it in a few lines determines the last one and returns this

'---------------------------------------------------------------------------------------
'-- Michel Posseth [MCP]
'-- Created on : 15-03-2009
'-- http:\\www.vbdotnetcoder.com
'-- info@xxxxxx
'---------------------------------------------------------------------------------------
Option Compare Binary
Option Explicit On
Option Strict On
Option Infer On
Imports System.IO
Imports System.Text
Public Class ClsReadTextFileReversed
Implements IDisposable
Private _FileToReadReverse As String
Public Property FileToReadReverse() As String
Get
If Not My.Computer.FileSystem.FileExists(_FileToReadReverse)
Then
Throw New ArgumentException("Property doesn`t contain file
path")
End If
Return _FileToReadReverse
End Get
Private Set(ByVal value As String)
If Not My.Computer.FileSystem.FileExists(value) Then
Throw New ArgumentException("File does not exist")
End If
_FileToReadReverse = value
End Set
End Property
Public Sub New(ByVal FullFilePath As String)
Me.FileToReadReverse = FullFilePath
End Sub
Private _Sr As StreamReader
Public Property Sr() As StreamReader
Get
Return _Sr
End Get
Private Set(ByVal value As StreamReader)
_Sr = value
End Set
End Property
Private _Fs As FileStream
Public Property Fs() As FileStream
Get
Return _Fs
End Get
Private Set(ByVal value As FileStream)
_Fs = value
End Set
End Property
Private _filesize As Long
Public Property Filesize() As Long
Get
Return _filesize
End Get
Private Set(ByVal value As Long)
_filesize = value
End Set
End Property
Private Function Init() As Boolean
Dim ret As Boolean
If Not Initialized Then
Try
Fs = New FileStream(FileToReadReverse, FileMode.Open,
FileAccess.Read, FileShare.Read)
Sr = New StreamReader(Fs, True)
Filesize = Sr.BaseStream.Length
Initialized = True
ret = True
Catch ex As Exception
RaiseEvent eException(ex)
ret = False
End Try
Else
ret = True
End If
Return ret
End Function
Public Event eException(ByVal ex As Exception)
Private _Initialized As Boolean
Public Property Initialized() As Boolean
Get
Return _Initialized
End Get
Private Set(ByVal value As Boolean)
_Initialized = value
End Set
End Property
Private _newline As String = Environment.NewLine
Public Property Newline() As String
Get
Return _newline
End Get
Set(ByVal value As String)
_newline = value
End Set
End Property
Private _SplitOption As StringSplitOptions =
StringSplitOptions.RemoveEmptyEntries
Public Property SplitOption() As StringSplitOptions
Get
Return _SplitOption
End Get
Set(ByVal value As StringSplitOptions)
_SplitOption = value
End Set
End Property
Public Function ReadLastLine() As String
Dim ret As String = String.Empty
If Init() Then
Dim buffersize As Long = 1024

buffersize = Math.Min(Filesize, buffersize)
Sr.BaseStream.Seek(-buffersize, SeekOrigin.End)

Dim text As String = Sr.ReadToEnd
Dim lines As String() = text.Split(New String() {Newline},
SplitOption)
Dim n As Integer = 4

If lines.Length <= n Then
If lines.Length < n Then
n = lines.Length
End If
If Filesize = buffersize + 1 Then
n -= 1
ElseIf Filesize >= buffersize + 2 Then
If lines(0) = "" OrElse lines(0)(0) <> ControlChars.Lf
Then
Sr.BaseStream.Seek(-buffersize - 2,
SeekOrigin.[End])
If Not (Sr.Read() = 13 AndAlso Sr.Read() = 10) Then
n -= 1
End If
Else
Sr.BaseStream.Seek(-buffersize - 1,
SeekOrigin.[End])
If Not (Sr.Read() = 13) Then
n -= 1
Else
lines(0) = lines(0).Substring(1)
End If
End If
End If
End If

Sr.Close()
Dim lastLines As String()

If n < lines.Length Then
lastLines = New String(n - 1) {}
If n > 0 Then
Array.Copy(lines, lines.Length - n, lastLines, 0, n)
End If
Else
lastLines = lines
End If
ret = lastLines(lastLines.Length - 1)
End If
Return ret
End Function
Public Sub Close()
If Sr IsNot Nothing Then
Sr.Close()
Sr.Dispose()
Sr = Nothing
End If
If Fs IsNot Nothing Then
Fs.Close()
Fs.Dispose()
Fs = Nothing
End If
End Sub
#Region " IDisposable Support "
Private disposedValue As Boolean = False ' To detect redundant
calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
If Sr IsNot Nothing Then
Sr.Close()
Sr.Dispose()
Sr = Nothing
End If
If Fs IsNot Nothing Then
Fs.Close()
Fs.Dispose()
Fs = Nothing
End If
' TODO: free other state (managed objects).
End If

' TODO: free your own state (unmanaged objects).
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' This code added by Visual Basic to correctly implement the disposable
pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal
disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class


'






"Tony Bansten" <tonytony@xxxxxx> schreef in bericht
news:49bcbeab$0$31869$9b4e6d93@xxxxxx-online.net...
Quote:

> How can I read the last non-blank (=non whitespace) line from a text file?
>
> Ok, the most primitive way would be to start reading from the beginning
> and then loop
> through all the lines until the end.
>
> But that is rather unconvenient and cumbersome.
>
> Is there a smarter way?
>
> Tony
>
My System SpecsSystem Spec
Old 03-15-2009   #7 (permalink)
Al Dunbar


 
 

Re: How to read the LAST NON-BLANK line from a text file?


"Michel Posseth" <msdn@xxxxxx> wrote in message
news:O$mVJPapJHA.5980@xxxxxx
Quote:

> The most primitive way is what the luxury coders can do and that is
> reading the whole file split it and then loop in reverse order
> however if you once processed files of gigagbytes in size then you
> understand that this isn`t going to work in all situations your app will
> blow up ( out of memory )
> or it will become verry slow .
>
> The following piece of code solves this problem as it only reads a peace
> of the end of the file and then split the lines
> so it doesn`t loop through a large file it reads a chunk at the end and
> then splits it in a few lines determines the last one and returns this
Please spare me having to read your script to determine this, but, what does
it do when it detects that it did not read a big enough chunk of the end of
the file to capture the last non-blank line?

/Al
Quote:

> '---------------------------------------------------------------------------------------
> '-- Michel Posseth [MCP]
> '-- Created on : 15-03-2009
> '-- http:\\www.vbdotnetcoder.com
> '-- info@xxxxxx
> '---------------------------------------------------------------------------------------
> Option Compare Binary
> Option Explicit On
> Option Strict On
> Option Infer On
> Imports System.IO
> Imports System.Text
> Public Class ClsReadTextFileReversed
> Implements IDisposable
> Private _FileToReadReverse As String
> Public Property FileToReadReverse() As String
> Get
> If Not My.Computer.FileSystem.FileExists(_FileToReadReverse)
> Then
> Throw New ArgumentException("Property doesn`t contain file
> path")
> End If
> Return _FileToReadReverse
> End Get
> Private Set(ByVal value As String)
> If Not My.Computer.FileSystem.FileExists(value) Then
> Throw New ArgumentException("File does not exist")
> End If
> _FileToReadReverse = value
> End Set
> End Property
> Public Sub New(ByVal FullFilePath As String)
> Me.FileToReadReverse = FullFilePath
> End Sub
> Private _Sr As StreamReader
> Public Property Sr() As StreamReader
> Get
> Return _Sr
> End Get
> Private Set(ByVal value As StreamReader)
> _Sr = value
> End Set
> End Property
> Private _Fs As FileStream
> Public Property Fs() As FileStream
> Get
> Return _Fs
> End Get
> Private Set(ByVal value As FileStream)
> _Fs = value
> End Set
> End Property
> Private _filesize As Long
> Public Property Filesize() As Long
> Get
> Return _filesize
> End Get
> Private Set(ByVal value As Long)
> _filesize = value
> End Set
> End Property
> Private Function Init() As Boolean
> Dim ret As Boolean
> If Not Initialized Then
> Try
> Fs = New FileStream(FileToReadReverse, FileMode.Open,
> FileAccess.Read, FileShare.Read)
> Sr = New StreamReader(Fs, True)
> Filesize = Sr.BaseStream.Length
> Initialized = True
> ret = True
> Catch ex As Exception
> RaiseEvent eException(ex)
> ret = False
> End Try
> Else
> ret = True
> End If
> Return ret
> End Function
> Public Event eException(ByVal ex As Exception)
> Private _Initialized As Boolean
> Public Property Initialized() As Boolean
> Get
> Return _Initialized
> End Get
> Private Set(ByVal value As Boolean)
> _Initialized = value
> End Set
> End Property
> Private _newline As String = Environment.NewLine
> Public Property Newline() As String
> Get
> Return _newline
> End Get
> Set(ByVal value As String)
> _newline = value
> End Set
> End Property
> Private _SplitOption As StringSplitOptions =
> StringSplitOptions.RemoveEmptyEntries
> Public Property SplitOption() As StringSplitOptions
> Get
> Return _SplitOption
> End Get
> Set(ByVal value As StringSplitOptions)
> _SplitOption = value
> End Set
> End Property
> Public Function ReadLastLine() As String
> Dim ret As String = String.Empty
> If Init() Then
> Dim buffersize As Long = 1024
>
> buffersize = Math.Min(Filesize, buffersize)
> Sr.BaseStream.Seek(-buffersize, SeekOrigin.End)
>
> Dim text As String = Sr.ReadToEnd
> Dim lines As String() = text.Split(New String() {Newline},
> SplitOption)
> Dim n As Integer = 4
>
> If lines.Length <= n Then
> If lines.Length < n Then
> n = lines.Length
> End If
> If Filesize = buffersize + 1 Then
> n -= 1
> ElseIf Filesize >= buffersize + 2 Then
> If lines(0) = "" OrElse lines(0)(0) <> ControlChars.Lf
> Then
> Sr.BaseStream.Seek(-buffersize - 2,
> SeekOrigin.[End])
> If Not (Sr.Read() = 13 AndAlso Sr.Read() = 10) Then
> n -= 1
> End If
> Else
> Sr.BaseStream.Seek(-buffersize - 1,
> SeekOrigin.[End])
> If Not (Sr.Read() = 13) Then
> n -= 1
> Else
> lines(0) = lines(0).Substring(1)
> End If
> End If
> End If
> End If
>
> Sr.Close()
> Dim lastLines As String()
>
> If n < lines.Length Then
> lastLines = New String(n - 1) {}
> If n > 0 Then
> Array.Copy(lines, lines.Length - n, lastLines, 0, n)
> End If
> Else
> lastLines = lines
> End If
> ret = lastLines(lastLines.Length - 1)
> End If
> Return ret
> End Function
> Public Sub Close()
> If Sr IsNot Nothing Then
> Sr.Close()
> Sr.Dispose()
> Sr = Nothing
> End If
> If Fs IsNot Nothing Then
> Fs.Close()
> Fs.Dispose()
> Fs = Nothing
> End If
> End Sub
> #Region " IDisposable Support "
> Private disposedValue As Boolean = False ' To detect redundant
> calls
> ' IDisposable
> Protected Overridable Sub Dispose(ByVal disposing As Boolean)
> If Not Me.disposedValue Then
> If disposing Then
> If Sr IsNot Nothing Then
> Sr.Close()
> Sr.Dispose()
> Sr = Nothing
> End If
> If Fs IsNot Nothing Then
> Fs.Close()
> Fs.Dispose()
> Fs = Nothing
> End If
> ' TODO: free other state (managed objects).
> End If
>
> ' TODO: free your own state (unmanaged objects).
> ' TODO: set large fields to null.
> End If
> Me.disposedValue = True
> End Sub
> ' This code added by Visual Basic to correctly implement the disposable
> pattern.
> Public Sub Dispose() Implements IDisposable.Dispose
> ' Do not change this code. Put cleanup code in Dispose(ByVal
> disposing As Boolean) above.
> Dispose(True)
> GC.SuppressFinalize(Me)
> End Sub
> #End Region
> End Class
>
>
> '
>
>
>
>
>
>
> "Tony Bansten" <tonytony@xxxxxx> schreef in bericht
> news:49bcbeab$0$31869$9b4e6d93@xxxxxx-online.net...
Quote:

>> How can I read the last non-blank (=non whitespace) line from a text
>> file?
>>
>> Ok, the most primitive way would be to start reading from the beginning
>> and then loop
>> through all the lines until the end.
>>
>> But that is rather unconvenient and cumbersome.
>>
>> Is there a smarter way?
>>
>> Tony
>>

My System SpecsSystem Spec
Old 03-15-2009   #8 (permalink)
Todd Vargo


 
 

Re: How to read the LAST NON-BLANK line from a text file?

Tony Bansten wrote:
Quote:

> How can I read the last non-blank (=non whitespace) line from a text file?
>
> Ok, the most primitive way would be to start reading from the beginning
and then loop
Quote:

> through all the lines until the end.
>
> But that is rather unconvenient and cumbersome.
>
> Is there a smarter way?
Acquiring the last non-blank line without reading entire (large) file line
by line is simple. Knowing what you intend to do with it requires that you
provide more information. I will assume you just want to display it...

'Captures last non-blank (=non whitespace) line from a text file.
Const ForReading = 1
Dim fso, f, fname, fsize, s, lastline

fname = "myfile.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(fname)
fsize = f.Size

Set f = fso.OpenTextFile(fname, ForReading)
If fsize > 2048 Then
f.Skip(fsize - 2048)
f.SkipLine
End If

Do While Not f.AtEndOfStream
s = f.ReadLine
If Not Trim(Replace(s, Chr(9), "")) = "" Then
lastline = s
End If
Loop

Wscript.Echo lastline

--
Todd Vargo
(Post questions to group only. Remove "z" to email personal messages)

My System SpecsSystem Spec
Old 03-16-2009   #9 (permalink)
Michel Posseth


 
 

Re: How to read the LAST NON-BLANK line from a text file?



The most primitive way is what the luxury coders can do and that is reading
the whole file split it and then loop in reverse order
however if you once processed files of gigagbytes in size then you
understand that this isn`t going to work in all situations your app will
blow up ( out of memory )
or it will become verry slow .

The following piece of code solves this problem as it only reads a peace of
the end of the file and then split the lines
so it doesn`t loop through a large file it reads a chunk at the end and then
splits it in a few lines determines the last one and returns this

'---------------------------------------------------------------------------------------
'-- Michel Posseth [MCP]
'-- Created on : 15-03-2009
'-- http:\\www.vbdotnetcoder.com
'-- info@xxxxxx
'---------------------------------------------------------------------------------------
Option Compare Binary
Option Explicit On
Option Strict On
Option Infer On
Imports System.IO
Imports System.Text
Public Class ClsReadTextFileReversed
Implements IDisposable
Private _FileToReadReverse As String
Public Property FileToReadReverse() As String
Get
If Not My.Computer.FileSystem.FileExists(_FileToReadReverse)
Then
Throw New ArgumentException("Property doesn`t contain file
path")
End If
Return _FileToReadReverse
End Get
Private Set(ByVal value As String)
If Not My.Computer.FileSystem.FileExists(value) Then
Throw New ArgumentException("File does not exist")
End If
_FileToReadReverse = value
End Set
End Property
Public Sub New(ByVal FullFilePath As String)
Me.FileToReadReverse = FullFilePath
End Sub
Private _Sr As StreamReader
Public Property Sr() As StreamReader
Get
Return _Sr
End Get
Private Set(ByVal value As StreamReader)
_Sr = value
End Set
End Property
Private _Fs As FileStream
Public Property Fs() As FileStream
Get
Return _Fs
End Get
Private Set(ByVal value As FileStream)
_Fs = value
End Set
End Property
Private _filesize As Long
Public Property Filesize() As Long
Get
Return _filesize
End Get
Private Set(ByVal value As Long)
_filesize = value
End Set
End Property
Private Function Init() As Boolean
Dim ret As Boolean
If Not Initialized Then
Try
Fs = New FileStream(FileToReadReverse, FileMode.Open,
FileAccess.Read, FileShare.Read)
Sr = New StreamReader(Fs, True)
Filesize = Sr.BaseStream.Length
Initialized = True
ret = True
Catch ex As Exception
RaiseEvent eException(ex)
ret = False
End Try
Else
ret = True
End If
Return ret
End Function
Public Event eException(ByVal ex As Exception)
Private _Initialized As Boolean
Public Property Initialized() As Boolean
Get
Return _Initialized
End Get
Private Set(ByVal value As Boolean)
_Initialized = value
End Set
End Property
Private _newline As String = Environment.NewLine
Public Property Newline() As String
Get
Return _newline
End Get
Set(ByVal value As String)
_newline = value
End Set
End Property
Private _SplitOption As StringSplitOptions =
StringSplitOptions.RemoveEmptyEntries
Public Property SplitOption() As StringSplitOptions
Get
Return _SplitOption
End Get
Set(ByVal value As StringSplitOptions)
_SplitOption = value
End Set
End Property
Public Function ReadLastLine() As String
Dim ret As String = String.Empty
If Init() Then
Dim buffersize As Long = 1024

buffersize = Math.Min(Filesize, buffersize)
Sr.BaseStream.Seek(-buffersize, SeekOrigin.End)

Dim text As String = Sr.ReadToEnd
Dim lines As String() = text.Split(New String() {Newline},
SplitOption)
Dim n As Integer = 4

If lines.Length <= n Then
If lines.Length < n Then
n = lines.Length
End If
If Filesize = buffersize + 1 Then
n -= 1
ElseIf Filesize >= buffersize + 2 Then
If lines(0) = "" OrElse lines(0)(0) <> ControlChars.Lf
Then
Sr.BaseStream.Seek(-buffersize - 2,
SeekOrigin.[End])
If Not (Sr.Read() = 13 AndAlso Sr.Read() = 10) Then
n -= 1
End If
Else
Sr.BaseStream.Seek(-buffersize - 1,
SeekOrigin.[End])
If Not (Sr.Read() = 13) Then
n -= 1
Else
lines(0) = lines(0).Substring(1)
End If
End If
End If
End If

Sr.Close()
Dim lastLines As String()

If n < lines.Length Then
lastLines = New String(n - 1) {}
If n > 0 Then
Array.Copy(lines, lines.Length - n, lastLines, 0, n)
End If
Else
lastLines = lines
End If
ret = lastLines(lastLines.Length - 1)
End If
Return ret
End Function
Public Sub Close()
If Sr IsNot Nothing Then
Sr.Close()
Sr.Dispose()
Sr = Nothing
End If
If Fs IsNot Nothing Then
Fs.Close()
Fs.Dispose()
Fs = Nothing
End If
End Sub
#Region " IDisposable Support "
Private disposedValue As Boolean = False ' To detect redundant
calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
If Sr IsNot Nothing Then
Sr.Close()
Sr.Dispose()
Sr = Nothing
End If
If Fs IsNot Nothing Then
Fs.Close()
Fs.Dispose()
Fs = Nothing
End If
' TODO: free other state (managed objects).
End If

' TODO: free your own state (unmanaged objects).
' TODO: set large fields to null.
End If
Me.disposedValue = True
End Sub
' This code added by Visual Basic to correctly implement the disposable
pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal
disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class


'






"Tony Bansten" <tonytony@xxxxxx> schreef in bericht
news:49bcbeab$0$31869$9b4e6d93@xxxxxx-online.net...
Quote:

> How can I read the last non-blank (=non whitespace) line from a text file?
>
> Ok, the most primitive way would be to start reading from the beginning
> and then loop
> through all the lines until the end.
>
> But that is rather unconvenient and cumbersome.
>
> Is there a smarter way?
>
> Tony
>
My System SpecsSystem Spec
Old 03-16-2009   #10 (permalink)
Pegasus [MVP]


 
 

Re: How to read the LAST NON-BLANK line from a text file?


"Todd Vargo" <tlvargo@xxxxxx> wrote in message
news:OGu%23YMdpJHA.3896@xxxxxx
Quote:

> Tony Bansten wrote:
Quote:

>> How can I read the last non-blank (=non whitespace) line from a text
>> file?
>>
>> Ok, the most primitive way would be to start reading from the beginning
> and then loop
Quote:

>> through all the lines until the end.
>>
>> But that is rather unconvenient and cumbersome.
>>
>> Is there a smarter way?
>
> Acquiring the last non-blank line without reading entire (large) file line
> by line is simple. Knowing what you intend to do with it requires that you
> provide more information. I will assume you just want to display it...
>
> 'Captures last non-blank (=non whitespace) line from a text file.
> Const ForReading = 1
> Dim fso, f, fname, fsize, s, lastline
>
> fname = "myfile.txt"
>
> Set fso = CreateObject("Scripting.FileSystemObject")
> Set f = fso.GetFile(fname)
> fsize = f.Size
>
> Set f = fso.OpenTextFile(fname, ForReading)
> If fsize > 2048 Then
> f.Skip(fsize - 2048)
> f.SkipLine
> End If
>
> Do While Not f.AtEndOfStream
> s = f.ReadLine
> If Not Trim(Replace(s, Chr(9), "")) = "" Then
> lastline = s
> End If
> Loop
>
> Wscript.Echo lastline
>
> --
> Todd Vargo
> (Post questions to group only. Remove "z" to email personal messages)
I think you overlooked something in your code. It fails not unexpectedly if
text file has more than around 1000 blank lines (each terminated by CRLF)
after the last non-blank line, as demonstrated by this modified version of
your example.

const iEmptyLines = 1100
Dim fso, f, fname, fsize, s, lastline

fname = "d:\temp\test.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(fname, 2)
f.WriteLine "This is the last line"
f.WriteBlankLines iEmptyLines
f.Close

Set f = fso.GetFile(fname)
fsize = f.Size

Set f = fso.OpenTextFile(fname, 1)
If fsize > 2048 Then
f.Skip(fsize - 2048)
f.SkipLine
End If

Do While Not f.AtEndOfStream
s = f.ReadLine
If Not Trim(Replace(s, Chr(9), "")) = "" Then
lastline = s
End If
Loop

WScript.Echo lastline


My System SpecsSystem Spec
Reply

Thread Tools


Similar Threads
Thread Forum
read text file - but starting at a specific point (not the very first character of the very first line) VB Script
Read a line from a text file, without loading the entire file inmemory PowerShell
The next line in a text file PowerShell
How do I read a text file and sort text by fixed positions? PowerShell
blank line in txt file problem PowerShell


Vista Forums is an independent web site and has not been authorized,
sponsored, or otherwise approved by Microsoft Corporation.
"Windows Vista", the Start Orb, and related materials are trademarks of Microsoft Corp.
© Designer Media Ltd

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46