Click here to Skip to main content
15,889,931 members
Articles / Programming Languages / VBScript
Tip/Trick

Comparing Two Files Line by Line

Rate me:
Please Sign up or sign in to vote.
2.54/5 (4 votes)
22 Nov 2020CPOL1 min read 6.7K   110   1
Windows batch utility in VBscript to read and compare two text files line by line
This is a small Windows batch utility written in VBscript to read and compare two text files line by line. It can read multiple files if folders are provided. It also supports sorting (.NET required) prior to comparison.

Introduction

This is a small and simple Windows batch utility that reads and compares two textual files line by line. It takes in two parameters (path1 and path2), which can be either file or folder paths. It also supports sorting by using .NET's System.Collections.ArrayList object.

Using the Code

The executable is run independently, without providing parameters as arguments. The parameters (path1 and path2) are collected through user prompts. The paths can be entered as relative or absolute paths (if relative paths are used, Shell.CurrentDirectory is added in front.

VBScript
Dim sh: Set sh = CreateObject("Wscript.Shell")
' ...
If Replace(path1,":","") = path1 Then
    If Left(path1,1) <> "\" Then path1 = "\" & path1
    path1 = sh.CurrentDirectory & path1
End If

Sorting functionality is provided through the internal call of VBscript code, it can be switched on / off by providing Y / N as argument:

BAT
set "psort=Y"

%cscript% //nologo "%~f0?.wsf" %psort% //job:VBS

If sorting is chosen, each file's lines shall be read into System.Collections.ArrayList objects and sorted by using its .Sort method:

VBScript
Set arrlist1 = CreateObject("System.Collections.ArrayList")
Do Until file1.AtEndOfStream
    arrlist1.Add file1.ReadLine
Loop
arrlist1.Sort

Then, a simple comparison is done - depending on whether sort is used or not, the lines will be read either from arrlist1 and arrlist2, or directly from the files.

Output

The program will report each line in the files that is not matching.

If multiple files are compared, then it will try to find the matching files in path2 by using the matching name from path1. If the file is not found, it will be reported as "not found".

Also, if a file has more lines than the other, this will be reported as "Other file has more lines".

The Complete Code

BAT
set "caption=Compare line by line"
title=%caption%
pushd "%~dp0"
@echo off
cls
if EXIST "C:\Windows\SysWOW64\" (set "cscript=C:\Windows\SysWOW64\cscript.exe") _
ELSE (set cscript=cscript.exe)
echo:

set "psort=Y"

%cscript% //nologo "%~f0?.wsf" %psort% //job:VBS

pause

exit

<package><job id="VBS"><script language="VBScript">
VBScript
Dim sort: sort = False
If WScript.Arguments(0) = "Y" Then sort = True

Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim sh: Set sh = CreateObject("Wscript.Shell")
Dim file1
Dim file2
Dim folder1
Dim folder2
Dim cnt
Dim errcnt

Dim path1
Dim path2

WScript.stdout.Write "Path 1: "
path1 = WScript.stdin.ReadLine
wscript.echo
WScript.stdout.Write "Path 2: "
path2 = WScript.stdin.ReadLine

' is relative path?
If Replace(path1,":","") = path1 Then
    If Left(path1,1) <> "\" Then path1 = "\" & path1
    path1 = sh.CurrentDirectory & path1
End If
If Replace(path2,":","") = path2 Then
    If Left(path2,1) <> "\" Then path2 = "\" & path2
    path2 = sh.CurrentDirectory & path2
End If

If fso.FolderExists(path1) And fso.FolderExists(path2) Then ' folders
    Set folder1 = fso.GetFolder(path1)
    Set folder2 = fso.GetFolder(path2)
    For Each fil In folder1.Files
        CompareFiles fil.Path, Replace(fil.Path, path1, path2), sort
    Next
ElseIf fso.FileExists(path1) And fso.FileExists(path2) Then ' files
    CompareFiles path1, path2, sort
Else
    WScript.Echo "Invalid path(s)!"
End If

WScript.Quit

Sub CompareFiles(fil1, fil2, sort)
    WScript.echo
    WScript.echo "Comparing files:"
    WScript.echo fil1
    WScript.echo fil2
    WScript.echo "==================================================="
    WScript.stdout.Write "Press [ENTER] to continue..."
    WScript.stdin.readline
    cnt = 1
    errcnt = 0
    If Not fso.FileExists(fil1) Then
        WSCript.echo "File " & fil1 & " does not exist!"
    ElseIf Not fso.FileExists(fil2) Then
        WScript.echo "File " & fil2 & " does not exist!"
    Else
        Set file1=fso.OpenTextFile(fil1)
        Set file2=fso.OpenTextFile(fil2)
        If sort Then
            Set arrlist1 = CreateObject("System.Collections.ArrayList")
            Do Until file1.AtEndOfStream
                arrlist1.Add file1.ReadLine
            Loop
            Set arrlist2 = CreateObject("System.Collections.ArrayList")
            Do Until file2.AtEndOfStream
                arrlist2.Add file2.ReadLine
            Loop
            arrlist1.Sort
            arrlist2.Sort
            Do: For i = 0 To Min(arrlist1.Count - 1, arrlist2.Count - 1)
                If i = arrlist1.Count - 1 And i <> arrlist2.Count - 1 Then
                    WScript.echo fil1 & " at end of stream: " & CStr(i) & " lines. _
                    Other file has more lines"
                    errcnt = errcnt + 1
                    Exit Do
                ElseIf i <> arrlist1.Count - 1 And i = arrlist2.Count - 1 Then
                    WScript.echo fil2 & " at end of stream: " & CStr(i) & " lines. _
                    Other file has more lines"
                    errcnt = errcnt + 1
                    Exit Do
                End If
                If arrlist1.Item(i) <> arrlist2.Item(i) Then
                    WScript.echo "Line " & CStr(i+1) & " mismatch"
                    errcnt = errcnt + 1
                End If
            Next: Loop While 0=1
        Else
            Do Until file1.AtEndOfStream And file2.AtEndOfStream
                If file1.AtEndOfStream And Not file2.AtEndOfStream Then
                    WScript.echo fil1 & " at end of stream: " & CStr(cnt-1) & " lines. _
                    Other file has more lines"
                    errcnt = errcnt + 1
                    Exit Do
                ElseIf file2.AtEndOfStream And Not file1.AtEndOfStream Then
                    WScript.echo fil2 & " at end of stream: " & CStr(cnt-1) & " lines. _
                    Other file has more lines"
                    errcnt = errcnt + 1
                    Exit Do
                End If
                If file1.readline <> file2.readline Then
                    WScript.echo "Line " & CStr(cnt) & " mismatch"
                    errcnt = errcnt + 1
                End If
                cnt = cnt + 1
            Loop
        End If
        If errcnt = 0 Then WScript.echo "Files match!"
        file1.close
        file2.close
    End If
End Sub

function Min(a,b)
    Min = a
    If b < a then Min = b
end function
BAT
</script></job></package>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
User Interface Analyst Raiffeisenbank Austria
Croatia Croatia
I acquired Masters degree in computing science at the Faculty of Electrical Engineering and Computing in Zagreb, Croatia in 2009. Following my studies, I got a job in a Croatian branch of Austrian-based CEE Raiffeisen Bank as an MIS (Management information system) analyst.
I have been working there since 2010, as an IT expert within the Controlling department, maintaining the Oracle's OFSA system, underlying interfaces and databases.
Throughout that time, I have worked with several different technologies, which include SQL & PL/SQL (mostly), postgres, Cognos BI, Apparo, Datastage, ODI, Jenkins, Qlik, ...
I am doing a lot of automation with scripting in batch / shell and VBscript (mostly) - data analysis and processing, automated DB imports and exports, Jenkins automation etc.
Privately, I was mostly doing Windows Forms and Console app tools in Visual Studio, C#.

Comments and Discussions

 
GeneralCompare 2 files output only about number of lines Pin
Salam Y. ELIAS13-Dec-20 6:45
professionalSalam Y. ELIAS13-Dec-20 6:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.