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!

4 Responses 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

  2. on 09 Mar 2021 at 7:15 pm NEYMAR

    Either you run the day or the day runs you

  3. on 09 Mar 2021 at 7:15 pm NEYMAR

    Concentrate all your thoughts upon the work in hand

  4. on 29 Mar 2021 at 6:23 pm NEYMAR

    Life is trying things to see if they work

Did I get this wrong? Let me know!

Trackback URI | Comments RSS