Feed on
Posts
Comments

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 


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

One Response to “use a perl one-liner to count the number of matches on the command-line”

  1. on 28 May 2010 at 2:59 pm Brian

    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

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.