脚本不会在" ="分隔符

时间:2014-07-07 15:37:43

标签: vbscript

以下脚本可用于查找重复项。

但我正在阅读的大部分文件都遵循以下格式:

ServerName(1) = "Example1"
ServerName(2) = "Example1"
ServerName(3) = "Example3"
ServerName(4) = "Example4"
ServerName(5) = "Example5"

下面代码中的'cut'变量应该在"="分隔符处剪切字符串,并返回"="分隔符后面的值。 它应写入重复文件"Example1",但不写入任何内容。我如何制作它以便下面的脚本读取文件,并且只在"="分隔符之后找到重复的值。

Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")



FileName = "Test.txt"
PathToSave = "C:"



Path = (PathToSave &  FileName)
Set objFile = objFSO.OpenTextFile(Path, ForReading)
Set objOutputFile = objFSO.OpenTextFile(PathToSave & "Noduplicates.txt", 2, True)
Set objOutputFile2 = objFSO.OpenTextFile(PathToSave & "Duplicates.txt", 2, True)

objOutputFile.WriteLine ("This document contains the " & path & " file without duplicates" & vbcrlf)
objOutputFile2.WriteLine ("This document contains the duplicates found. Each line listed below had a duplicate in " & Path & vbcrlf)
Dim DuplicateCount
DuplicateCount = 0
Set Dict = CreateObject("Scripting.Dictionary")
Do until objFile.atEndOfStream
    strCurrentLine = LCase(Trim(objFile.ReadLine))
    Cut = Split(strCurrentline,"=")

    If not Dict.Exists(LCase(Trim(cut(strCurrentLine)))) then 
        objOutputFile.WriteLine strCurrentLine
        Dict.Add strCurrentLine,strCurrentLine
    Else Dict.Exists(LCase(Trim(cut(strCurrentLine))))
        objOutputFile2.WriteLine strCurrentLine
        DuplicateCount = DuplicateCount + 1
    End if 
Loop

If DuplicateCount > 0 then
    wscript.echo ("Number of Duplicates Found: " & DuplicateCount)
Else 
    wscript.echo "No Duplicates found"
End if

2 个答案:

答案 0 :(得分:1)

Cut是您的数组,因此Cut(1)=之后的部分。所以你应该在你的词典中测试n#39;

If InStr(strCurrentline, "=") > 0 Then

    Cut = Split(strCurrentline,"=")

    If Not Dict.Exists(Cut(1)) then 
        objOutputFile.WriteLine strCurrentLine
        Dict.Add Cut(1), Cut(1)
    Else
        objOutputFile2.WriteLine strCurrentLine
        DuplicateCount = DuplicateCount + 1
    End if 

End If

答案 1 :(得分:-2)

我完全没理由要求Split通过将第3个参数设置为1来返回带有 one 元素的数组,如

Cut = Split(strCurrentline,"=",1)

证据:

>> WScript.Echo Join(Split("a=b", "=", 1), "*")
>>
a=b
>> WScript.Echo Join(Split("a=b", "="), "*")
>>
a*b

BTW:ServerName(5) = "Example5"应该在" =&#34 ;;进一步考虑引用可能是可取的。

更新wrt评论(和downvotes):

根据文档计算参数的语义:

  

计数

Optional. Number of substrings to be returned; -1 indicates that all substrings are returned. If omitted, all substrings are returned.

要求一个元素(不是UBound!)会导致一个元素包含输入。

证据类型不匹配错误:

>> cut = Split("a=b", "=", 1)
>> WScript.Echo cut
>>
Error Number:       13
Error Description:  Type mismatch
>>

所以请三思。