jonathan
jonathan

Reputation: 291

How can I sort after using a delimiter on the last field in bash scripting

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 :)

Upvotes: 2

Views: 303

Answers (3)

potong
potong

Reputation: 58381

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

Upvotes: 1

sehe
sehe

Reputation: 392911

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 (<>);

Upvotes: 0

Havenless
Havenless

Reputation: 116

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.

Upvotes: 2

Related Questions