如何计算文本文件中以日期开头的行数

how to count the number of lines in a text file that start with a date

我有一个文件,其内容为

2004-10-07     cva        create file ...
2003-11-11     cva        create version ...
2003-11-11     cva        create version ...
2003-11-11     cva        create branch ...

现在我想计算这个特定文件中以日期开头的行数。 我该怎么做

如果我使用 wc -l <file.txt>
它给了我总行数(在我的例子中是 5,而我想要的是计数应该是 4)

一种简单易行的方法:Perl

你的文件

2004-10-07     cva 
2004-10-04             
anything
2004-10-07     cva 
anything
2004-10-07     cva 
2004-10-07     cva 

你需要
perl -lne ' ++$n if /^\d+-\d+-\d+/; print $n' your-file

输出

1  
2  
2  
3  
3  
4  
5  

计数并只打印总和
perl -lne ' ++$n if /^\d+-\d+-\d+/ ;END{ print $n}' your-file

输出
5


with egrep -c 计算匹配数
cat your-file | egrep -c '^[0-9]+-[0-9]+-[0-9]+'

输出
5

给定:

$ cat file
2004-10-07     cva        create file ...
no date
2003-11-11     cva        create version ...
no date
2003-11-11     cva        create version ...
no date
2003-11-11     cva        create branch ...

首先弄清楚如何 运行 在文件的每一行上使用正则表达式。假设您使用 sed 因为它是相当标准和快速的。您还可以使用 awkgrepbashperl

这是一个sed解决方案:

$ sed -nE '/^[12][0-9]{3}-[0-9]{2}-[0-9]{2}/p' file
2004-10-07     cva        create file ...
2003-11-11     cva        create version ...
2003-11-11     cva        create version ...
2003-11-11     cva        create branch ...

然后将其通过管道传输到 wc:

$ sed -nE '/^[12][0-9]{3}-[0-9]{2}-[0-9]{2}/p' file | wc -l
      4

或者,您可以在 awk 中使用相同的模式而不需要使用 wc:

$ awk '/^[12][0-9]{3}-[0-9]{2}-[0-9]{2}/{lc++} END{ print lc }' file
4

或者,相同的模式,grep

$ grep -cE '^[12][0-9]{3}-[0-9]{2}-[0-9]{2}' file
4

(注意:不清楚您的日期格式是 YYYY-MM-DD 还是 YYYY-DD-MM 如果已知,您可以使模式更具体。)