VB脚本 - 在同一文本文件中查找重复项

时间:2014-09-17 04:16:07

标签: vbscript

我是VBScript的新手,我正在尝试:

  • 阅读文本文件并查找重复项
  • 将重复行复制到另一个文本文件

我已经拥有以下代码。我谷歌我的问题,但大多数答案是两个文件之间的比较。知道怎么继续吗?

Dim Thistextfile, fso, obj, things
Const ForReading = 1

Thistextfile = "C:\Listofthings.txt"
Set fso = CreateObject("Scripting.FileSystemObject")

Set obj = fso.OpenTextFile(Thistextfile,ForReading)

Do Until obj.AtEndOfStream
things = obj.ReadLine
things = Trim(things)
    If Len(things) > 0 Then
        WScript.Echo things
    End If
Loop

obj.close

1 个答案:

答案 0 :(得分:1)

您可以将每一行收集到dictionary.Net's ArrayList中,然后将每一行写入新文件(如果该文件已存在于该文件中):

Dim Thistextfile, fso, obj, things
Const ForReading = 1

Thistextfile = "C:\Listofthings.txt"
Set fso = CreateObject("Scripting.FileSystemObject")

Set obj = fso.OpenTextFile(Thistextfile,ForReading)

dim dictionary: set dictionary = CreateObject("Scripting.Dictionary")
dictionary.CompareMode = 1 'vbTextCompare
dim outputfile: set outputfile = fso.CreateTextFile("c:\duplicates.txt", true, true)

Do Until obj.AtEndOfStream
    things = obj.ReadLine()
    things = Trim(things)
    If Len(things) > 0 Then
        WScript.Echo things
    End If

    'if it already exists, it's a duplicate
    if dictionary.exists(things) then
        outputfile.writeline things
    else
        dictionary.add things, null
    end if
Loop

outputfile.close
obj.close