Search code examples
vbscriptreadfile

Skipping one line while reading a .txt file


I am trying to read through a .txt file that says:

"If you are"
"Reading this"
"It worked!"

I am trying to have only "If you are" and "It worked!" appear, skipping over the middle line "Reading this". My code exits the loop and only shows "If you are". How can I change this?

'Declare variables
Dim objFSO, objReadFile, contents 

'Set Objects
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objReadFile = objFSO.OpenTextFile("M:\vbscripts\folder\read.txt") 

'Read file contents
Do While objReadFile.AtEndOfStream <> True
    contents = objReadFile.ReadLine
    If contents = "Reading this" then
        Exit Do
    End If
    WScript.Echo contents 
Loop

'Quit script
WScript.Quit()

Solution

  • Don't exit from the loop when you encounter the line you want to skip over. Instead output lines only if they don't contain the text in question:

    Do Until objReadFile.AtEndOfStream
        contents = objReadFile.ReadLine
        If Not InStr(contents, "Reading this") > 0 then
            WScript.Echo contents 
        End If
    Loop