in reply to sort file with your own logic

Note that there is also a -h option for sort on some systems. For those that lack it I have been using this code, piping the du -h output to it. The %so look-up hash gives to sort order for the scale suffix and allows for systems that use no suffix for bytes as well as those that use "B" instead.

use strict; use warnings; use Getopt::Std; my %opts = ( a => 0 ); getopts( q{a}, \ %opts ) or die qq{\n}; my %so = ( q{} => 0, B => 0, K => 1, M => 2, G => 3, T => 4, E => 5, P => 6, Z => 7, Y => 8, ); my $rcSortAscending = sub { my( $raA, $raB ) = @_; return $so{ $raA->[ 2 ] } <=> $so{ $raB->[ 2 ] } || $raA->[ 1 ] <=> $raB->[ 1 ] }; print map { my( $line, $path ) = @$_[ 0, 3 ]; if ( $path !~ m{/$} and -d $path and not -l $path ) { $line =~ s{\n}{/\n}; } $line; } sort { $opts{ a } ? $rcSortAscending->( $a, $b ) : $rcSortAscending->( $b, $a ) } map { [ $_, m{^\s*([\d.]+)([BKMGTEPZY]?)\s+(.*)} ] } <>;

I hope this is helpful.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: sort file with your own logic
by Anonymous Monk on Mar 27, 2015 at 19:57 UTC

    How will that sort "4321K" vs "2M"? Sorting by normalized value would be my preference.

    sub val { m/([\d.]*)([BKMGTEPZY]?)/ and $1 * $scale{$2} } ... sort { val($a) <=> val($b) } ...