代码之家  ›  专栏  ›  技术社区  ›  Mario Palumbo

是否有bash-perl快捷方式来计算每行中的匹配数?

  •  0
  • Mario Palumbo  · 技术社区  · 2 月前

    这是一个类似的问题,但会计算整个文件中的匹配项:

    Is there a Perl shortcut to count the number of matches in a string?

    相反,我希望在bash上使用perl逐行计算匹配数。

    例子: ~/test.txt

    one.two.three.four
    one.two.three.four
    one.two.three.four
    one.two.three.four
    

    这是我使用的bash命令行:

    perl -0777snE 'my @count = /\./gm; say scalar @count' -- ~/test.txt
    

    返回内容:

    12
    

    相反,我希望它逐行计数并返回给我:

    3
    3
    3
    3
    

    我怎样才能得到这个?

    1 回复  |  直到 2 月前
        1
  •  1
  •   Gilles Quénot ticktalk    2 月前

    简单:

    $ perl -nE 'my @count = /\./gm; say scalar @count' file
    3
    3
    3
    3
    

    不要使用 -0777 如果你不需要它。


    如果你需要它:

    perl -0777 -nE 'do{ my @count = /\./gm; say scalar @count } for split /\n/' file