use a perl one-liner to count the number of matches on the command-line
May 13th, 2008 by Lawrence David
let’s say you’ve got a string and you’d like to count the number of times some substring appears in it. let’s also assume that you’re lazy and you don’t want to leave your shell terminal to do it.  fortunately, there’s an easy way to count string matches from the command-line using a perl one-liner.   let’s say we want to count the number of commas in the text file my_file.txt. all you need to write is:Â
$Â perl -nle ‘print tr/,/,/;’ < my_file.txtÂ
This is great for a single-line file. Thanks.
To get total matches on a multi-line file I ended up doing
perl -lne ‘$a += tr/,//; END {print $a}’ my_file.txt
Either you run the day or the day runs you
Concentrate all your thoughts upon the work in hand
Life is trying things to see if they work