从文件中的特定字符串中读取前一行

时间:2015-12-09 18:40:51

标签: vbscript

我正在尝试使用VBScript从文本文件中读取特定行。首先,我在文本文件中搜索一个特定的字符串,然后尝试读取该特定字符串上方的4 th 行。

示例:假设,我正在寻找一个字符串' CAT'在文本文件中。我在第1763行找到了这个字符串。现在,我正在尝试编写第no行的内容。 1759.我知道我没有以正确的方式循环获取字符串一旦我得到行没有。请建议。

Dim Count
Dim strline

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\PSi\Both.txt", ForReading)

Const ForReading = 1
Count = 0

Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    Count=Count+1
    If instr(strLine, "CAT") <> 0 Then
        Count = Count-4
        Exit Do
    End If 
Loop
'This section of code not working..
'Error : Input past end of file 
For i=1 To Count-4
    objFile.ReadLine
Next
strline = objFile.ReadLine
MsgBox strline

objFile.Close

2 个答案:

答案 0 :(得分:0)

是的,因为你已经遍历了objFile,你到了最后,它试图回到最后。而不是尝试两次运行文件的内容,将文件保存到一个数组中,并根据需要多次浏览。

Dim a, text: a = "C:\testenv\test.log"
text = split(CreateObject("Scripting.FileSystemObject").OpenTextFile(a, 1).ReadAll, vbcrlf)

'Round 1
for i=0 to ubound(text)
    'operate on each line here text(i)
next

'Round 2
for i=0 to ubound(text)
    'operate on each line here text(i)
next

答案 1 :(得分:0)

您无法向后读取文件(除非您将整个文件读入数组,如果您有大文件,这可能会耗尽内存),但您可以使用ring buffer来保存以前的文件从文件中读取的n行:

filename = "C:\Users\PSi\Both.txt"
bufsize  = 5 'number of lines to keep in the ring buffer

Set fso = CreateObject("Scripting.FileSystemObject")

'create and initialize ring buffer
ReDim buf(bufsize-1)
For n = 0 To UBound(buf)
  buf(n) = Null
Next

i = 0
matchFound = False

'read lines into ring buffer
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream Or matchFound
  buf(i) = f.ReadLine
  If InStr(buf(i), "CAT") > 0 Then matchFound = True
  i = (i+1) Mod bufsize
Loop
f.Close

如果缓冲区已完全填充,则数组元素buf(i)现在包含您要查找的行(从文件读取的最后一行之前的第4行)。否则,如果从文件中读取的行少于5行,则可以“快进”到第一个非null元素:

j = 0
Do While IsNull(buf(i)) And j < bufsize
  i = (i+1) Mod bufsize
  j = j + 1
Loop
相关问题