Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting on the last field of a line

What is the simplest way to sort a list of lines, sorting on the last field of each line? Each line may have a variable number of fields.

Something like

sort -k -1 

is what I want, but sort(1) does not take negative numbers to select fields from the end instead of the start.

I'd also like to be able to choose the field delimiter too.

Edit: To add some specificity to the question: The list I want to sort is a list of pathnames. The pathnames may be of arbitrary depth hence the variable number of fields. I want to sort on the filename component.

This additional information may change how one manipulates the line to extract the last field (basename(1) may be used), but does not change sorting requirements.

e.g.

/a/b/c/10-foo /a/b/c/20-bar /a/b/c/50-baz /a/d/30-bob /a/e/f/g/h/01-do-this-first /a/e/f/g/h/99-local 

I want this list sorted on the filenames, which all start with numbers indicating the order the files should be read.

I've added my answer below which is how I am currently doing it. I had hoped there was a simpler way - maybe a different sort utility - perhaps without needing to manipulate the data.

like image 778
camh Avatar asked Jul 11 '10 11:07

camh


People also ask

How do I sort a field in Linux?

Use the -k option to sort on a certain column. For example, use " -k 2 " to sort on the second column.


2 Answers

awk '{print $NF,$0}' file | sort | cut -f2- -d' ' 

Basically, this command does:

  1. Repeat the last field at the beginning, separated with a whitespace (default OFS)
  2. Sort, resolve the duplicated filenames using the full path ($0) for sorting
  3. Cut the repeated first field, f2- means from the second field to the last
like image 177
François Rousseau Avatar answered Sep 29 '22 07:09

François Rousseau


Here's a Perl command line (note that your shell may require you to escape the $s):

perl -e "print sort {(split '/', $a)[-1] <=> (split '/', $b)[-1]} <>" 

Just pipe the list into it or, if the list is in a file, put the filename at the end of the command line.

Note that this script does not actually change the data, so you don't have to be careful about what delimeter you use.

Here's sample output:

 >perl -e "print sort {(split '/', $a)[-1] <=> (split '/', $b)[-1]} " files.txt /a/e/f/g/h/01-do-this-first /a/b/c/10-foo /a/b/c/20-bar /a/d/30-bob /a/b/c/50-baz /a/e/f/g/h/99-local 
like image 40
Gabe Avatar answered Sep 29 '22 06:09

Gabe