Sort by multiple columns in bash

Alex picture Alex · Dec 19, 2016 · Viewed 16.7k times · Source

I have a file with 2 columns, "Name" and "Age", looking like this:

Alex,  15
Mary,  12
Alex,  28
Zoe,   16
Alex,  17

I will sort by the first column in alphabetical order, using sort -t ',' -k1,1 filename.txt, but if there are same names, I want the 2nd column to be sorted in the reversed way of how they were in the original file, like this:

Alex,  17
Alex,  28
Alex,  15
Mary,  12
Zoe,   17

How can I do this?

Answer

Tomáš Šíma picture Tomáš Šíma · Dec 19, 2016

Read file from back, sort by the first column and -s to preserve order in case of same value

tac filename.txt | sort -k1,1 -s
...
Alex,  17
Alex,  28
Alex,  15
Mary,  12
Zoe,   16