Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by multiple columns in bash

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?

like image 534
Alex Avatar asked Dec 19 '16 21:12

Alex


People also ask

How do I sort a file in Bash by column?

How to Sort In Linux Bash by Column Sort allows us to sort a file by columns by using the -k option. Let us start by creating a file with more than one column. In sort, we separate a column by a single space.

How do I sort a file with more than one column?

Let us start by creating a file with more than one column. In sort, we separate a column by a single space. In the example file below, we have six columns. To sort the captains’ file above by their century, we can specify the -k followed by the column number as:

How to sort data using the sort command in Excel?

Once we specify the column to sort the data, the sort command will try to sort the values in ascending order. In the example above, the command sorts the values from the earliest century to the latest. To sort by the first name, set the sort column as 1: To save the sorted output to a file, we can use the -o option as:

How many types of sort options are there in Bash?

The sort command comes with 31 options (13 main and 18 categorized as other). Most experienced bash programming (even experts) know only a few main sort options required to get by. Others are seldom touched. Lucky for you we have time to touch them all.


1 Answers

sort -t ',' -k1,1 -k2,2r filename.txt

or

sort -t ',' -k1,1 -k2r,2 filename.txt

The output is:

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

Explain: -t is to specify the field-separator, -k can be used to specify the start and stop position of field, and we could add a single letter OPTS for that field for ordering, for example r means to reverse the result of comparisons.

like image 197
lqxyz Avatar answered Oct 08 '22 07:10

lqxyz