[Linux-users] Sort Question

Kurt Wall kwall
Fri Aug 3 06:54:06 PDT 2007


On Aug 2, 2007, at 5:01 PM, tom marinis wrote:

[needs to sort this by line and field within a line]

> less sourcefile.txt
>
> 3:51:12:74:41:43:13
> 8:33:36:37:39:41:9
> 1:6:23:24:27:39:34
>

Yah, you're abusing sort. sort will handle line-by-line sorting
just fine, but to sort the colon-delimited fields within each
line, you'll have to that in a separate step. That is, sort sorts
by line. I've never seen it used to sort /within/ a line.

Here's some non-idiomatic perl that should do the trick. First,
though, here's how to use it (using the three lines of input above):

$ ./sortline.pl < unsorted | sort -g
1:6:23:24:27:34:39
3:12:13:41:43:51:74
8:9:33:36:37:39:41

Here's the code
#!/usr/bin/perl

while (<>) {
         # lose the trailing newline
         chomp $_;

         # split the input on ":"
         @nums = split /:/;

         # sort the values numerically
         @sorted = sort {$a <=> $b} @nums;

         # rebuild and display the colon-delimited record
         $lineout = join ':', (@sorted);
         print "$lineout\n";
}

If it breaks, you get to keep both pieces.



More information about the Linux-users mailing list