我有一个包含大约100K行的文本文件。现在我想从文本文件中搜索一个字符串。如果该字符串存在,那么我想得到它所在的行号。最后,我需要使用文本文件中的行号出现该字符串。
*尝试普通方法* 我们可以逐行阅读整个文本文件。保持每次读取后增加的计数器变量。如果我找到了我的字符串,那么我将返回Counter Variable。这种方法的局限是,我必须逐个遍历所有100K行来搜索字符串。这会降低性能。
*快速方法(需要帮助)* 是否有任何方法可以直接将我带到我的searchstring所在的行,如果找到,我可以返回它所在的行号。
*示例*
考虑下面的数据存在于文本文件中。 (比如说只有5行)
现在我想搜索一个字符串说“Pune”。现在搜索之后,它应该返回字符串“pune”存在的行号。在这种情况下,它出现在第2行。我应该得到“2”作为输出。我想用行号
搜索所有“pune”的出现答案 0 :(得分:1)
我使用了Me How的代码示例来查看搜索字符串的~10,000个文件的列表。另外,由于我的html文件有可能在几行中包含字符串,并且我想要交错输出,我将其更改了一点并添加了单元格插入片段。我只是在学习,但这正是我所需要的,我希望它可以帮助别人。
Public Sub ReadTxtFile()
Dim start As Date
start = Now
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFS As Object
Dim filePath As String
Dim a, b, c, d, e As Integer
a = 2
b = 2
c = 3
d = 2
e = 1
Dim arr() As String
Do While Cells(d, e) <> vbNullString
filePath = Cells(d, e)
ReDim arr(5000) As String
Dim i As Long
i = 0
If oFSO.FileExists(filePath) Then
On Error GoTo Err
Set oFS = oFSO.OpenTextFile(filePath)
Do While Not oFS.AtEndOfStream
arr(i) = oFS.ReadLine
i = i + 1
Loop
oFS.Close
Else
MsgBox "The file path is invalid.", vbCritical, vbNullString
Exit Sub
End If
For i = LBound(arr) To UBound(arr)
If InStr(1, arr(i), "Clipboard", vbTextCompare) Then
Debug.Print i + 1, arr(i)
Cells(a + 1, b - 1).Select
Selection.Insert Shift:=xlDown
Cells(a, b).Value = i + 1
Cells(a, c).Value = arr(i)
a = a + 1
d = d + 1
End If
Next
a = a + 1
d = d + 1
Loop
Debug.Print DateDiff("s", start, Now)
Exit Sub
Err:
MsgBox "Error while reading the file.", vbCritical, vbNullString
oFS.Close
Exit Sub
End Sub
答案 1 :(得分:0)
以下片段可以修复如下:
Dim arr() As String
Dim i As Long
i = 0
If oFSO.FileExists(filePath) Then
On Error GoTo Err
Set oFS = oFSO.OpenTextFile(filePath)
Do While Not oFS.AtEndOfStream
ReDim Preserve arr(0 To i)
arr(i) = oFS.ReadLine 'to save line's content to array
'If Len(oFSfile.ReadLine) = 0 Then Exit Do 'to get number of lines only
i = i + 1
Loop
oFS.Close
Else
MsgBox "The file path is invalid.", vbCritical, vbNullString
Exit Sub
End If
答案 2 :(得分:0)
这是另一种应该相当快速运作的方法。它使用shell来执行FINDSTR命令。如果您发现cmd框闪烁,请在互联网上搜索如何禁用它。提供了两个选项:一个将返回行号,后跟冒号和包含关键字的行的文本。另一个只返回行号。
不确定您要对结果做什么,所以我只是将它们放在消息框中。
Option Explicit
'Set reference to Windows Script Host Object Model
Sub FindStrings()
Const FindStr As String = "Pune"
Const FN As String = "C:\users\ron\desktop\LineNumTest.txt"
Dim WSH As WshShell
Dim StdOut As Object
Dim S As String
Set WSH = New WshShell
Set StdOut = WSH.Exec("cmd /c findstr /N " & FindStr & Space(1) & FN).StdOut
Do Until StdOut.AtEndOfStream
S = S & vbCrLf & StdOut.ReadLine
'If you want ONLY the line number, then
'S = S & vbCrLf & Split(StdOut.ReadLine, ":")(0)
Loop
S = Mid(S, 2)
MsgBox (S)
End Sub