sed or awk to order a file

Hi -

I have a file with lots of lines in that I need to order based on the number of commas!

e.g the file looks something like :-
cn=john,cn=users,cn=uk,dc=dot,dc=com
cn=john,cn=users,dc=com
cn=users,cn=groups,dc=com
cn=john,cn=admins,cn=users,cn=uk,dc=dot,dc=com
cn=fred,cn=users,cn=uk,dc=dot,dc=com
cn=simon,cn=users,cn=uk,dc=dot,dc=com
cn=users,dc=com

I need to order the file so that it ends up like :-
cn=john,cn=admins,cn=users,cn=uk,dc=dot,dc=com
cn=john,cn=users,cn=uk,dc=dot,dc=com
cn=fred,cn=users,cn=uk,dc=dot,dc=com
cn=simon,cn=users,cn=uk,dc=dot,dc=com
cn=john,cn=users,dc=com
cn=users,cn=groups,dc=com
cn=users,dc=com

I am hoping someone knows some sed or awk that can do this ? :slight_smile:

Many thanks

There could be a better way to do this, but this may help...

awk -F"," '{print NF ":" $0}' datafile | /bin/sort -t: +0 -1 -n -r | awk -F":" '{print $2}'

If Perl is acceptable:

perl -e'print sort{$b=~tr/,//<=>$a=~tr/,//}<>' infile

Otherwise:

awk -F, '{ print NF "\t" $0 }' infile | 
  sort -rn | 
    cut -f2-

GNU awk:

WHINY_USERS=oops awk -F, 'END {
  for (n in f) s[i++] = f[n]
  while (i--) print s
  }  
{ f[NF] = NF in f ? f[NF] RS $0 : $0 }
' infile

Great answers ... thanks for the help :slight_smile:

my @lines=<DATA>;
print map {$_->[0]}
sort {$b->[1] <=> $a->[1]}
map {[$_,tr/,//]} @lines;
__DATA__
cn=john,cn=users,cn=uk,dc=dot,dc=com
cn=john,cn=users,dc=com
cn=users,cn=groups,dc=com
cn=john,cn=admins,cn=users,cn=uk,dc=dot,dc=com
cn=fred,cn=users,cn=uk,dc=dot,dc=com
cn=simon,cn=users,cn=uk,dc=dot,dc=com
cn=users,dc=com