Hey, Scripting Guy! How can I count the number of lines in a text file?
Hey, MS. It’s easy to tell that Microsoft’s scripting technologies weren’t written by people who do system administration for a living. Our scripting technologies are jam-packed with features and capabilities, yet we always seem to missing the things that people really want to do. Counting the number of lines in a text file is a good example of that. This seems to be something system administrators do on a regular basis; after all, this is the fourth or fifth time we’ve been asked this question just this month. And yet, there’s no straightforward way to count the number of lines in a text. Is there a CountLines method somewhere? Nope. How about a NumberOfLines property? Nope. Go figure.
Fortunately, while our scripting technologies aren’t always straightforward, they usually are flexible enough to provide a workaround. And this is no exception. While there might not be an obvious way to count the number of lines in a text file, you can still use a script to get at this information. For example, this script returns the number of lines found in the file C:\Scripts\Test.txt:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
Wscript.Echo "Number of lines: " & objTextFile.Line
So what’s the secret here? Well, we begin by using the FileSystemObject to open the file for reading. Next we simply read the entire text file, using the ReadAll method. When we use ReadAll, we read in every line of the text file. Because the FileSystem object can only read from the beginning of a file to the end of the file, that means that when ReadAll is finished we must be on the very last line of the file; it’s impossible for us to be anywhere else. Consequently, all we have to do is echo the value of the Line property, which reports the line number of the current line. Because we are on the last line, the Line property in this case also tells us the number of lines in the file. Simple.
Of course, you might be thinking, “Oh, sure, open up and read an entire file just to get the line count? How long will that take?” Surprisingly enough, not very long at all. We tested this script on a text file with just over 20,000 lines. On a regular old laptop computer (2.39 GhZ, 512 MB of RAM) the script took 1 second to complete. Your results might vary, but they probably won’t vary by much