quorious quorious - 1 year ago 69
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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download