Script / sort question; sort on last field of a line?
Alex Beamish
talexb-Re5JQEeQqe8AvxtiuMwx3w at public.gmane.org
Thu May 4 19:49:17 UTC 2006
A possible solution in Perl:
----------------------------------
#!/usr/bin/perl -w
# Sort using the last word of each line.
use strict;
use warnings;
my %hash;
while(<>) {
# Strip any newline, split line into words.
chomp;
my @a=split(/ /,$_);
# Stuff the line into a hash of arrays, using the last word as the hash
key.
push(@{$hash{$a[-1]}},$_);
}
# Dump out the sorted (using the default sorting algorithim) results from
the
# hash.
foreach my $key ( sort keys %hash ) {
# Within each key there may be several lines; dump them out in the order
# that they were encountered.
foreach(@{$hash{$key}}) {
print "$_\n";
}
}
# Done.
----------------------------------
To sort on the second to last field, change the '-1' to '-2'; you can also
subsitute your own sort algorithim after the word 'sort'. You can also
change what consitutes a 'word' by changing the delimiter in the split
statement.
--
Alex Beamish
Toronto, Ontario
On 5/4/06, Walter Dnes <waltdnes-SLHPyeZ9y/tg9hUCZPvPmw at public.gmane.org> wrote:
>
> How do I sort on the last (or 2nd last or whatever) field of a line?
>
> One awkward possibility involves rewriting the lines backwards,
> sorting on what is now the first field, and rewriting the lines
> backwards a second time. I'm not aware of a utility to do write lines
> backwards. I am *NOT* thinking of "tac" which writes the lines
> unaltered but reverses their order. I want to write *EACH INDIVIDUAL
> LINE* backwards. The following script does what I want...
>
> #!/bin/bash
> while read
> do
> line_out=""
> line_pointer=$(( ${#REPLY} - 1 ))
> while [[ ${line_pointer} -ge 0 ]]
> do
> line_out="${line_out}${REPLY:${line_pointer}:1}"
> line_pointer=$(( ${line_pointer} - 1 ))
> done
> echo "${line_out}"
> done
>
> --
> Walter Dnes <waltdnes-SLHPyeZ9y/tg9hUCZPvPmw at public.gmane.org> In linux /sbin/init is Job #1
> My musings on technology and security at http://tech_sec.blog.ca
> --
> The Toronto Linux Users Group. Meetings: http://tlug.ss.org
> TLUG requests: Linux topics, No HTML, wrap text below 80 columns
> How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://gtalug.org/pipermail/legacy/attachments/20060504/e7b9a83a/attachment.html>
More information about the Legacy
mailing list