quorious quorious - 4 months ago 34
Perl Question

Replace set of characters with their number of occurrences

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

String is "aaaadddyyyyccccaaaa"

So it should output a4d3y4c4a4.

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


With perl

$ echo 'aaaadddyyyyccccaaaa' | perl -pe 's/(.)\1*/$1.length($&)/ge'
  • (.)\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