[英]How does this work to count number of lines in a file? no_of_lines=`<$file wc -l`
[英]Faster and precise way to count lines other than wc -l
通常,我使用wc -l
來計數文件的行數。 但是對於5 * 10 ^ 7行的文件,我只能得到10 ^ 7作為答案。 我已經嘗試過這里提出的所有建議: 如何計算文檔中的行數? 但這要比wc -l
花費更多的時間。
還有其他選擇嗎?
認真考慮速度線計數的任何人都可以創建自己的實現:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#define BUFFER_SIZE (1024 * 16)
char BUFFER[BUFFER_SIZE];
int main(int argc, char** argv) {
unsigned int lines = 0;
int fd, r;
if (argc > 1) {
char* file = argv[1];
if ((fd = open(file, O_RDONLY)) == -1) {
fprintf(stderr, "Unable to open file \"%s\".\n", file);
return 1;
}
} else {
fd = fileno(stdin);
}
while ((r = read(fd, BUFFER, BUFFER_SIZE)) > 0) {
char* p = BUFFER;
while ((p = memchr(p, '\n', (BUFFER + r) - p))) {
++p;
++lines;
}
}
close(fd);
if (r == -1) {
fprintf(stderr, "Read error.\n");
return 1;
}
printf("%d\n", lines);
return 0;
}
用法
a < input
... | a
a file
例:
# time ./wc temp.txt
10000000
real 0m0.115s
user 0m0.102s
sys 0m0.014s
# time wc -l temp.txt
10000000 temp.txt
real 0m0.120s
user 0m0.103s
sys 0m0.016s
*在使用GCC 4.8.2的具有AVX和SSE4.2的系統上以-O3
本地編譯的代碼。
嘗試使用nl,看看會發生什么...
您可以嘗試sed
sed -n '$=' file
=
表示打印行號,而美元表示僅在最后一行執行。 -n
表示不要做太多其他事情。
或者這是Perl中的一種方法,將其另存為wc.pl
並執行chmod +x wc.pl
:
#!/usr/bin/perl
use strict;
use warnings;
my $filename = <@ARGV>;
my $lines = 0;
my $buffer;
open(FILE, $filename) or die "ERROR: Can not open file: $!";
while (sysread FILE, $buffer, 65536) {
$lines += ($buffer =~ tr/\n//);
}
close FILE;
print "$lines\n";
像這樣運行它:
wc.pl yourfile
基本上,它一次讀取64kB塊中的文件,然后利用tr
請求刪除所有換行符后返回的替換次數這一事實。
取決於打開文件的方式,但可能可以從STDIN讀取文件,從而可以解決此問題:
wc -l < file
您可以像下面一樣使用awk
獲取行數
awk 'END {print NR}' names.txt
(OR)使用while .. do .. done
bash循環構造
CNT=0; while read -r LINE; do (( CNT++ )); done < names.txt; echo $CNT
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.