Bash – Sorting data based on second column of a file

bashshellunix

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.

Best Answer

You can use the sort command:

sort -k2 -n yourfile

-n, --numeric-sort compare according to string numerical value

For example:

$ cat ages.txt 
Bob 12
Jane 48
Mark 3
Tashi 54

$ sort -k2 -n ages.txt 
Mark 3
Bob 12
Jane 48
Tashi 54