1

假设我有两个文本文件,我将比较(基于文本的行号 -> 见下文),因为这是生成唯一键的地方。

样本1.txt:

5th line -> _000_000F_01CE2577.B840E640

样本2.txt

5th line -> _000_000F_01CE2577.B840E640

现在这是我的代码:

            Dim FILE_NAME As String = "C:\myfiles"

            'This is to determine the number of lines in the text file
            Dim count As Integer
            count = 0

            Dim obj As StreamReader
            obj = New StreamReader(FILE_NAME)

            Do Until obj.ReadLine Is Nothing
                count = count + 1
            Loop

            '------------------------------
            'this is my computation to get the number of line -->disregard this

            Dim temp3 As Integer
            temp3 = count - 3
            '------------------------------

            obj.Close()

            'This is to read all the text in the text file
            Dim fileReader(fs) As String
            fileReader(fs) = My.Computer.FileSystem.ReadAllText(FILE_NAME, _
                        System.Text.Encoding.ASCII)

我已将每个文件存储在一个数组示例中:

             file[0]
             file[1]

然后我必须阅读每个文件及其内容,现在我将如何将文本行相互比较。我相信我必须使用正则表达式。

请给我一些有关如何比较文本行的指示...

例如 sample1.txt 的第 5 行 == sample2.txt 的第 5 行

我必须知道它们是否相同。

4

1 回答 1

1

这应该为您完成这项工作,
它将读取 txt 文件中的每一行,将其保存到一个数组然后比较
注意:设置路径执行您的 2 个 txt 文件
,如果文件 2 中的行数少于文件 1,它将超出范围。不过,您可以添加一些代码来处理这种情况。

Option Explicit

Sub Read_text_File()

    Dim firstFile() As String, secondFile() As String
    Dim path1 As String, path2 As String
    Dim i As Long

    path1 = "C:\ ... .txt"
    path2 = "C:\ ... .txt"

    Call fill_array(firstFile, path1)
    Call fill_array(secondFile, path2)

    For i = LBound(firstFile) To UBound(firstFile) - 1
        Debug.Print (firstFile(i) & vbTab & vbTab & vbTab & vbTab & secondFile(i))
        If StrComp(firstFile(i), secondFile(i), vbTextCompare) = 0 Then
            MsgBox "Line: " & i + 1 & "  matches "
        End If
    Next i

End Sub

Sub fill_array(ByRef arr() As String, pathToFile As String)

    Dim oFSO As New FileSystemObject
    Dim oFS As TextStream

    Dim cnt As Long
    cnt = 0

    Set oFS = oFSO.OpenTextFile(pathToFile)

    Do Until oFS.AtEndOfStream
        oFS.ReadLine
        cnt = cnt + 1
    Loop
    ReDim arr(cnt)
    Set oFS = oFSO.OpenTextFile(pathToFile)
    cnt = 0
    Do Until oFS.AtEndOfStream
        arr(cnt) = oFS.ReadLine
        cnt = cnt + 1
    Loop

    oFS.Close
    Set oFS = Nothing
End Sub
于 2013-03-20T12:00:47.350 回答