How to Sort a File Content in to either Alphabetic or Numeric Order (VBScript)

Send Us a Sign! (Contact Us!)
Word PDF Epub Text
XML XPS MHT

The easiest way to eliminate duplicate entries is going to utilizing a object that has the ability to see if an object exists (Scripting.Dictionary) or contains (System.Collections.ArrayList) an entry already.

Let's see a sample text file containing the following rows...

Servers.txt (Before)

SERVER1

SERVER2

SERVER3

SERVER4

SERVER2

SERVER5

SERVER1

SERVER6

SERVER3

SERVER4

SERVER5

The Script

Option Explicit

Const FOR_READING = 1

Const FOR_WRITING = 2

Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")

Dim arrLines : Set arrLines = CreateObject("System.Collections.ArrayList")

'Open the file

Dim objFile : Set objFile = objFSO.OpenTextFile("C:\servers.txt", FOR_READING, False)

'Loop thru and add each line to the array

Do Until objFile.AtEndOfStream

strLine = Trim(objFile.ReadLine)

'Verify that array doesn't already have the entry

If Not arrLines.Contains(strLine) Then arrLines.Add(strLine)

Loop

objFile.Close

'Sort (ascending) for aesthetics

arrLines.Sort()

'Join the array with vbCrLf (carriage return or enter)

Dim strNewFile : strNewFile = Join(arrLines.ToArray, vbCrLf)

'Re-open the file for reading

Set objFile = objFSO.OpenTextFile("C:\servers.txt", FOR_WRITING, False)

'Write the new text

objFile.Write strNewFile

objFile.Close

Servers.txt (After)

SERVER1

SERVER2

SERVER3

SERVER4

SERVER5

SERVER6
SOURCE

LINK

LANGUAGE
ENGLISH

1 thought on “How to Sort a File Content in to either Alphabetic or Numeric Order (VBScript)”

Comments are closed.