Ordering a string by the count of substrings?

How about

$ perl -F'-' -lpe '$_ = join "-", sort { length $a <=> length $b } @F' file
22-212-1234-11153782-0114232192380
14-234-6756-09867378-8807698823332
14-221-45323-43676256-238372635363
23-234-9983-62736373-8863345637388

and

$ perl -F'-' -lpe '$_ = join "-", sort { $a <=> $b } map length, @F' file
2-3-4-8-13
2-3-4-8-13
2-3-5-8-12
2-3-4-8-13

Thanks to Stéphane Chazelas for suggested improvements


GNU awk can sort, so the trickiest part is deciding how to separate the two desired outputs; this script generates both results, and you can decide if you'd like them somewhere other than hard-coded output files:

function compare_length(i1, v1, i2, v2) {
  return (length(v1) - length(v2));
}

BEGIN {
  PROCINFO["sorted_in"]="compare_length"
  FS="-"
}

{
        split($0, elements);
        asort(elements, sorted_elements, "compare_length");
        reordered="";
        lengths="";
        for (element in sorted_elements) {
                reordered=(reordered == "" ? "" : reordered FS) sorted_elements[element];
                lengths=(lengths == "" ? "" : lengths FS) length(sorted_elements[element]);
        }
        print reordered > "reordered.out";
        print lengths > "lengths.out";
}

How far would this get you:

awk -F- '               # set "-" as the field separator
{
 for (i=1; i<=NF; i++){
   L    = length($i)    # for every single field, calc its length
   T[L] = $i            # and populate the T array with length as index
   if (L>MX){ MX = L }  # keep max length
 }                        
 $0 = ""                # empty line
 for (i=1; i<=MX; i++){
  if (T[i]){
   $0 = $0 OFS T[i]     # append each non-zero T element to the line, separated by "-"
   C  = C OFS i         # keep the field lengths in separate variable C
  }
 }
 print substr ($0, 2) "\t"  substr (C, 2)    # print the line and the field lengths, eliminating each first char
 C = MX = ""                                 # reset working variables
 split ("", T)                               # delete T array
}
' OFS=- file
22-212-1234-11153782-0114232192380  2-3-4-8-13
14-234-6756-09867378-8807698823332  2-3-4-8-13
14-221-45323-43676256-238372635363  2-3-5-8-12
23-234-9983-62736373-8863345637388  2-3-4-8-13

You may want to split the printout into two result files.