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?
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.
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:
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With