I have a file of two columns and n
number of rows.
column 1 contains names
and column2 age
.
I want to sort the content of this file in ascending order based on the age
(in second column).
The result should display the name
of the youngest person along with name
and then second youngest person and so on...
Any suggestions for a one liner shell or bash script.
Use sort
.
sort ... -k 2,2 ...
sort -k 2 -n filename
more verbosely written as:
sort --key 2 --numeric-sort filename
$ cat filename
A 12
B 48
C 3
$ sort --key 2 --numeric-sort filename
C 3
A 12
B 48
-k # - this argument specifies the first column that will be used to sort. (note that column here is defined as a whitespace delimited field; the argument -k5
will sort starting with the fifth field in each line, not the fifth character in each line)
-n - this option specifies a "numeric sort" meaning that column should be interpreted as a row of numbers, instead of text.
Other common options include:
There are other options, but these are the most common and helpful ones, that I use often.
For tab separated values the code below can be used
sort -t$'\t' -k2 -n
-r can be used for getting data in descending order.
-n for numerical sort
-k, --key=POS1[,POS2] where k is column in file
For descending order below is the code
sort -t$'\t' -k2 -rn
Source: Stackoverflow.com