quorious quorious - 13 days ago 5
Perl Question

Replace set of characters with their number of occurrences

Hi i want to replace characters in String with their number of occurrences.
e.g


String is "aaaadddyyyyccccaaaa"

So it should output a4d3y4c4a4.


I'm thinking if it can be done by some command, rather than looping by program.

Answer

With perl

$ echo 'aaaadddyyyyccccaaaa' | perl -pe 's/(.)\1*/$1.length($&)/ge'
a4d3y4c4a4
  • (.)\1* any character followed by any number of repeats
  • $1.length($&) captured character and length of entire match
  • e modifier allows expression in replacement section