2

for example

suppose that from a command let's call it "previous" we get a result, this result contains lines of text

now before printing out this text, I want to use the sort command in order to sort it using a delimiter.

in this case the delimiter is "*"

the thing is, I always want to sort on the last field for example if a line is like that

text*text***text*********text..*numberstext

I want my sort to sort using the last field, in this case on numberstext

if all lines were as the line I just posted, then it would be easy

I can just count the fields that are being created when using a delimiter(suppose we have N fields) and then apply this command

previous command | sort -t * -k N -n

but not all lines are in the same form, some line can be like that:

text:::***:*numberstext

as you can see, I always want to sort using the last field

basically I'm looking for a method to find the last field when using as a delimiter the character *

I was thinking that it might be like that

previous command | sort -t * -k $some_variable_denoting_the_ammount_of_fields -n

but I'm not sure if there's anything like that..

thanks :)

3
  • you'll have to add a filter before sort to 'normalize' you data and ensure that each record has the same number of fields. Good luck. Commented Oct 30, 2011 at 20:51
  • but this is not possible, I want the output to be like the input but sorted, if I do it like you suggest, won't the output differ from the input? Commented Oct 30, 2011 at 20:52
  • yes, output will be diff. The other option is to write a custom sort in your favorite programming language. Got to go. Good luck. Commented Oct 30, 2011 at 20:53

3 Answers 3

2

Use sed to duplicate the final field at the start of the line, sort, then use sed to remove the duplicate. Probably simpler to use your favourite programming language though.

Sign up to request clarification or add additional context in comments.

Comments

1

This might work:

 sed -r 's/.*\*([^*]+$)/\1@@@&/' source | sort | sed 's/^.*@@@//'

Add the last field to the front, sort it, delete the sort key N.B. @@@ can be anything you like as long as it does not exist in the source file. Credit should go to @Havenless this is just his idea put into code

Comments

0

Here is a perl script for it:

#!/usr/bin/perl
use strict;
use warnings;

my $regex = qr/\*([^*]*)$/o;

sub bylast
{
    my $ak = ($a =~ $regex, $1) || "";
    my $bk = ($b =~ $regex, $1) || "";
    $ak cmp $bk;
}

print for sort bylast (<>);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.