【问题标题】:how to count the number of lines in a text file that start with a date如何计算文本文件中以日期开头的行数
【发布时间】:2017-02-08 16:23:19
【问题描述】:

我有一个内容为的文件

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

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

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

【问题讨论】:

  • grep "[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}" filename | wc -l 应该给出这种特定格式的行数。但是,使用 awk 会更好。

标签: regex bash clearcase wc


【解决方案1】:

给定:

$ 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,如果已知,您可以使模式更具体。)

【讨论】:

    【解决方案2】:

    一个简单的方法: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


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

    输出
    5

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 2020-10-31
      • 2016-11-02
      • 2011-03-29
      • 1970-01-01
      • 2013-04-17
      相关资源
      最近更新 更多