Batch - Getting the number of lines

September 10, 2007 at 23:09:25
Specs: windows, -
The question is how do I get the number of lines in a txt file useing a batch command(or just the number of the last line, which is the same)?

My problem is that I`m talking about files that are 20MB big, so I prefer not to scan all the "\n" in the file, or something like that.
I thought of maybe, is there a way of getting the Whole last line(with its line number) and from that getting just the line number.


See More: Batch - Getting the number of lines

Report •


#1
September 11, 2007 at 00:55:16
*NIX has the wc command, but that's no help to us. Instead, we must use for to walk though the file, counting as we go.
SET count=0
FOR /F "usebackq delims=" %a IN (yourFile.txt) DO SET /A count+=1
SET count

Oh, that'll also skip completely blank lines. Such is the nature of FOR.


Report •

#2
September 11, 2007 at 03:10:41
If you can set up a string that *absolutely* is never stored in the documents to be scanned, you can try

Find /V /C "nowhere string" your_file.txt

where "nowhere string" may be e.g. "$@$@".


Report •

#3
September 11, 2007 at 04:04:54
here's a vbscript alternative:
[code]
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
myFile = objArgs(0)
Set objFile = objFSO.OpenTextFile(myFile,1)
Do Until objFile.AtEndOfLine
line = objFile.Line
objFile.ReadLine
Loop
WScript.Echo "Line count of", myFile , "is", line
[/code]
usage:
cscript myscript myfile

Report •

Related Solutions

#4
September 11, 2007 at 04:42:37
ghost, wouldn't objFile.ReadAll work better here, or am I just too tired to think straight?

Report •

#5
September 11, 2007 at 04:49:09
What is a "whole" last line?
If the last line is not terminated with a CR, is it considered a line?

I think you have to count the newline characters. There is no way without sequentially scanning the whole file, except if the file consists of known same length lines.

There are line count utilities available. Just GOOGLE.


Report •

#6
September 11, 2007 at 07:34:37
raz, thanks for the reminder.
[code]
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objArgs = WScript.Arguments
myFile = objArgs(0)
Set objFile = objFSO.OpenTextFile(myFile,1)
objFile.ReadAll
line = objFile.Line
WScript.Echo "Line count of", myFile , "is", line
[/code]


Report •


Ask Question