Vbscript 从文件中的特定字符串读取前几行
我正在尝试使用VBScript从文本文件中读取特定行。首先,我在文本文件中搜索一个特定字符串,然后尝试读取该特定字符串上方的第四行 示例:假设我正在文本文件中查找字符串“CAT”。我在第1763行找到了这根绳子。现在,我正在写第1759行的内容。我知道,一旦我得到行号,我就没有以正确的方式循环得到字符串。请建议Vbscript 从文件中的特定字符串读取前几行,vbscript,Vbscript,我正在尝试使用VBScript从文本文件中读取特定行。首先,我在文本文件中搜索一个特定字符串,然后尝试读取该特定字符串上方的第四行 示例:假设我正在文本文件中查找字符串“CAT”。我在第1763行找到了这根绳子。现在,我正在写第1759行的内容。我知道,一旦我得到行号,我就没有以正确的方式循环得到字符串。请建议 Dim Count Dim strline Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile =
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
Dim计数
暗斯特林
设置objFSO=CreateObject(“Scripting.FileSystemObject”)
设置objFile=objFSO.OpenTextFile(“C:\Users\PSi\tware.txt”,用于读取)
常数ForReading=1
计数=0
直到objFile.AtEndOfStream
strLine=objFile.ReadLine
计数=计数+1
如果仪表(strLine,“CAT”)为0,则
计数=计数-4
退出Do
如果结束
环
'这段代码不起作用。。
'错误:输入超过文件末尾
对于i=1到计数-4
objFile.ReadLine
下一个
strline=objFile.ReadLine
MsgBox strline
objFile.Close
是的,因为您已经遍历了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
不能向后读取文件(除非将整个文件读入数组,如果文件较大,可能会耗尽内存),但可以使用保存从文件中读取的前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
j = 0
Do While IsNull(buf(i)) And j < bufsize
i = (i+1) Mod bufsize
j = j + 1
Loop
如果缓冲区已完全填满,则数组元素buf(i)
现在包含要查找的行(从文件读取的最后一行之前的第四行)。否则,如果从文件中读取的行数少于5行,则可以像这样“快进”到第一个非空元素:
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
j = 0
Do While IsNull(buf(i)) And j < bufsize
i = (i+1) Mod bufsize
j = j + 1
Loop
j=0
当IsNull(buf(i))和j