I want a vbscript which will output the difference between two text files and write the difference in 3rd text file. Please help.

5 Comments   [ + ] Show Comments


  • need a few more details...Is the file identical line by line with additional lines in one or the other, or is there random changes to one or the other?
    • Files are identical line by line with some additional lines.
  • Are the additional lines always at the end of the file? Or could they be in the middle? This will make a big difference in the complexity of the code required.
    • they could be in middle.
  • You know that "wheel" thingy you were talking about? Someone beat you to it.

    Use Beyond Compare. It has a CLI and can thus be driven by script.
  • That would be a good solution if he wanted to spend money. I use beyond compare myself and love it, but it's not free.
  • Thank you this is helpful...!
Please log in to comment



Here is my attempt. I based it from code from

http://www.perlmonks.org/?node_id=1016585 and http://blogs.technet.com/b/heyscriptingguy/archive/2007/05/24/how-can-i-compare-the-contents-of-two-text-files.aspx


Option Explicit
On Error Resume Next

Const ForReading = 1
Const TextCompare = 1

Dim File1, File2, OutputFile

File1 = "file1.txt"
File2 = "file2.txt"
OutputFile = "outfile.txt"

Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
If ObjFSO.FileExists(File1) Then
  Dim objFile1 : Set objFile1 = objFSO.OpenTextFile("file1.txt", ForReading)
End If

' Dictionary object for reference file.
Dim RefDict : Set RefDict = CreateObject("Scripting.Dictionary")
RefDict.CompareMode = TextCompare

Dim StrLine, SearchLine, strNotFound

' Read reference file into dictionary object.
Do Until objFile1.AtEndOfStream
  StrLine = Trim(objFile1.ReadLine)
  if Not RefDict.Exists(StrLine) Then
    RefDict.Add StrLine, "1"
  End If


' File that may have more or less lines.
If ObjFSO.FileExists(File2) Then
  Dim objFile2 : Set objFile2 = objFSO.OpenTextFile("file2.txt", ForReading)
End If

' Search 2nd file with reference file.
Do Until objFile2.AtEndOfStream
  SearchLine = Trim(objFile2.ReadLine)
  If Not RefDict.Exists(SearchLine) Then
    If IsEmpty(strNotFound) Then
      strNotFound = SearchLine
      strNotFound = strNotFound & vbCrLf & SearchLine
    End If
  End If


If IsEmpty(strNotFound) or strNotFound = "" Then
End If

Dim objFile3 : Set objFile3 = objFSO.CreateTextFile(OutputFile, True)

objFile3.WriteLine strNotFound
Answered 03/21/2014 by: flip1001
Third Degree Green Belt

Please log in to comment
Answer this question or Comment on this question for clarity