![](/img/trans.png)
[英]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.