I. Gü I. Gü - 1 year ago 55
Bash Question

Sort text in shell using last word before specific delimiter

How do I sort a text file alphabetically in shell using the last word before a certain delimiter as key?

E.g. the following file:

Manfred1 Mustermann1 (Berlin)
Manfred Siegfried Müller (Aachen)
Gerd A. Meier (Stuttgart)


In this case the delimiter would be " (" and I would like to sort using the last name of the persons in the list. The number of words before the last name is varying.

Given a line of text I know how to extract the key:

s="Manfred1 Mustermann1 (Berlin)"
w=${s%% (*}
l=${w##* }
echo $l


This displays "Mustermann1", but I did not get any further.

EDIT
Using l0b0's answer, this is the complete code that did it:

while read s; do
w=${s%% (*}
l=${w##* }
printf "%s\t%s\n" "$l" "$s"
done <names.txt | sort -k 1 | cut -f 2 > names_sorted.txt


where names.txt contains the text and the sorted list will be printed to names_sorted.txt

Answer Source

Once you've got the sort key ($l) you can proceed like this:

  1. Print the sort key followed by a tab character followed by the original line, as in printf %s\t%s\n.
  2. Use sort's --key option to sort by the first column (tab should be the default key separator).
  3. Remove the sort key and tab character by using awk or grep.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download