4

I'm running Windows 7 and have GnuWin32. I have a several-gigabyte text file with LF (\n) line endings. I want to know how many lines it has (or alternatively how many LFs it has, which is, let's say, one fewer, but I don't care). What's the fastest or least expensive way to get my answer?

Some possibilities (though I'm sure I'm missing some):

  • wc -l foo
  • grep -c $ foo (with -c, prints only the count of matching lines)
  • grep -c ^^ foo (the first caret escapes the second)
  • sed -n $= foo (-n prevents printing the line; $ restricts to the last line; = prints the line number)

(Those are the GnuWin32 utilities. I don't know of any native-to-Windows way.)

2
  • My answer gives a number of other possibilities. I will let you do the timings and let us all know which is the fastest ;)
    – DavidPostill
    Jul 17, 2015 at 23:07
  • Did you come to any conclusions?
    – DavidPostill
    Jul 26, 2015 at 13:30

2 Answers 2

4

Windows command line solution

type foo | find "" /v /c

Powershell solutions

(get-content foo | measure-object -line).lines

(dir foo | select-string .).count

(type foo).count

(gc foo | measure-object | select count).count

perl solution

perl -pe '}{$_=$.' foo

awk solution

awk 'END { print NR }' foo

Further reading

0

The fastest for me is the command line: find /v /c "" foo.txt

I am yet to do a proper benchmark but I tried type and (get-content foo | measure-object -line) for a 10GB file on a 2GB ram server, but they took far too long to complete. Find however returned fast enough

2
  • 1
    You propose a solution which is already suggested. Please pay an answer only if it provides additional information. Have you compared multiple ways? Which ones? What was the result? What was your test case? ... Oct 31, 2018 at 8:55
  • @MátéJuhász I didn't find it elsewhere, find command is not the same as type. Posted in a hurry but will update answer with more details. Oct 31, 2018 at 12:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .