Solved

sorting a list of numbers and strings

Posted on 2000-03-15
12
153 Views
Last Modified: 2010-03-05
Im trying to sort the output of a df -k top down. The problem is each line is a mix of a number then a tab and then the folder ie
1234      /usr/home/somebody
If I sort it, it does it alphabetically as they contain strings. I think if I use split to split them I can then sort the numbers but I want to keep a reference to the string part so the numbers and folders tally on output.
Any help appreciated.
0
Comment
Question by:orango
  • 4
  • 3
  • 3
  • +2
12 Comments
 
LVL 3

Expert Comment

by:guadalupe
ID: 2619628
Try this...the out put is a little ugly but you can re do it...

#!/usr/local/bin/perl

$lines = `du -k`;



@lines = split(/\n/, $lines);

%dus = map{(split/\s+/)[0,1]}@lines;

@keys = sort { $a <=> $b} (keys %dus);

foreach $key (@keys)
{
      print "$key = $dus{$key}\n";
}
0
 

Author Comment

by:orango
ID: 2619862
Im not brilliant at perl Im afraid and don't fully understand the code.It is virtually there but if file sizes happen to be the same it only reports back the last entry at that size. Im guessing that the filesize is being used as the key to the hash dus and overites the previous entry if it happens to be the same.

In this line can you tell me what the
[0,1] does. Is it part of the split or map.

%dus = map{(split/\s+/)[0,1]}@lines;

Thanks for the help
Regards
0
 
LVL 1

Expert Comment

by:builder110697
ID: 2620192
Try this.  It works for me.


#!/bin/perl

my $homedirs = "/usr/home";
open( TTT, "du -sk $homedirs/* |" );
foreach ( <TTT> ) {
  chomp;
  @tmp = split( /       /, $_ );
  $tmp[1] =~ s/\/..*\///;
  $diskspace{$tmp[1]} = $tmp[0];
}
close TTT;

print "  Username        Diskspace\n ----------      -----------\n";
foreach ( sort keys %diskspace ) {
  printf( "  %-12s %12d\n", $_, $diskspace{$_});
}
0
Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

 
LVL 84

Accepted Solution

by:
ozo earned 100 total points
ID: 2620723
print sort{$a<=>$b} `du -k`;
0
 
LVL 5

Expert Comment

by:PC_User321
ID: 2621259
I don't understand why you object to alphabetic sorting, because, since the sizes are presumably right aligned, an alphabetic sort will work fine.
This will sort alphabetically, top down:

print sort{$b cmp $a} `du -k`;

To do a _numeric_ sort, you have to isolate the numbers and sort according to them.
The line below extracts the size by using /^\s*(\d+)/, then sorts numerically (top down) using that as the key.

print sort{$b =~ /^\s*(\d+)/ <=> $a =~ /^\s*(\d+)/} `du -k`;
0
 
LVL 5

Expert Comment

by:PC_User321
ID: 2621655
Embarrassment!  
I did not test my earlier post.  Now I understand why alphabetical sort does not work.

The simplest solution is ozo's, modified for top down:
   print sort{$b<=>$a} `du -k`;

It complains about non-numeric values being used in a numeric comparison, but it works.

To clean it up you need to isolate the numeric part:
   print sort{($A = $a) =~ /\d+/; ($B = $b) =~ /\d+/; $B <=> $A} `du -k`;
0
 
LVL 84

Expert Comment

by:ozo
ID: 2621739
#Or turn off the warnings
{local $^W=0;print sort{$b <=> $a} `du -k`}

#(if you need to do more processing, like ($A = $a) =~ /\d+/ it may be worth using a Schwartzian Transform)
0
 
LVL 5

Expert Comment

by:PC_User321
ID: 2621793
For fun I tried a 1-liner that produces formatted output.
This works 98%
   print sort{$b cmp $a} map{s/(\d+)/sprintf("%10d", $1)/e, $_} `du -k`;

Perhaps someone could provide the missing 2%
0
 
LVL 84

Expert Comment

by:ozo
ID: 2621819
print sort map{s/\s*(\d+)/sprintf("%10d", $1)/e;$_} `du -k`;
0
 
LVL 5

Expert Comment

by:PC_User321
ID: 2621839
Good.  Without even using a Schw...whatever :)

Just needs a {$b cmp $a} to round it off.
0
 

Author Comment

by:orango
ID: 2622911
I copied your program but when I run it. It doesn't work correctly it will only print this
devel:~ # ./test.pl
  Username        Diskspace
 ----------      -----------
                          8
where as du -sk /home/* gives

1816    /home/admin
4       /home/bill
8       /home/bob

when run with -w gives

Use of uninitialized value at ./test.pl line 7, <TTT> chunk 3.
Use of uninitialized value at ./test.pl line 8, <TTT> chunk 3.
Use of uninitialized value at ./test.pl line 8, <TTT> chunk 3.
Use of uninitialized value at ./test.pl line 7, <TTT> chunk 3.
Use of uninitialized value at ./test.pl line 8, <TTT> chunk 3.
Use of uninitialized value at ./test.pl line 7, <TTT> chunk 3.
Use of uninitialized value at ./test.pl line 8, <TTT> chunk 3.
  Username        Diskspace
 ----------      -----------
Argument "8^I/home/bob" isn't numeric in prtf at ./test.pl line 14.
                          8

0
 

Author Comment

by:orango
ID: 2622933
Works fine. Ideal solution thank you all for your help.

Im not sure how it works but Ill keep reading the perl books !
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Migrate OTRS to newest version. 1 326
Insert Text into odbc.ini file 15 64
How to get all the API from website? 11 84
what are these modules in perl script 4 98
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question