Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

linux - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...