How do I sort a text file alphabetically in shell using the last word before a certain delimiter as key?
Eg 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
Once you've got the sort key ( $l
) you can proceed like this:
printf %s\\t%s\\n
. sort
's --key
option to sort by the first column (tab should be the default key separator). awk
or grep
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.