bashperlubuntu-22.04

Is there a bash-perl shortcut to count the number of matches in each line?


This is a similar question but counts the matches in the entire file:

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

Instead I want the number of matches to count line by line, using perl on bash.

Example: ~/test.txt

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

This is the bash command line I use:

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

Which returns:

12

Instead I want it to count line by line and return to me:

3
3
3
3

How can I get this?


Solution

  • Simple:

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

    Don't use -0777 if you don't need it.


    If you need it:

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