Count the number of lines in a file without reading entire file into memory?

前端 未结 15 1398
忘掉有多难
忘掉有多难 2020-12-24 01:38

I\'m processing huge data files (millions of lines each).

Before I start processing I\'d like to get a count of the number of lines in the file, so I can then indic

15条回答
  •  攒了一身酷
    2020-12-24 02:36

    Reading the file a line at a time:

    count = File.foreach(filename).inject(0) {|c, line| c+1}
    

    or the Perl-ish

    File.foreach(filename) {}
    count = $.
    

    or

    count = 0
    File.open(filename) {|f| count = f.read.count("\n")}
    

    Will be slower than

    count = %x{wc -l #{filename}}.split.first.to_i
    

提交回复
热议问题