Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting data based on second column of a file

Tags:

bash

shell

unix

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.

like image 630
Angelo Avatar asked Jun 22 '11 11:06

Angelo


People also ask

How do I sort a specific column in Linux?

Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.

How do I sort a column in bash?

Sort allows us to sort a file by columns by using the -k option.

How do I sort by column in Excel?

Select a cell in the column you want to sort. On the Data tab, in the Sort & Filter group, click Sort. In the Sort dialog box, under Column, in the Sort by or Then by box, select the column that you want to sort by a custom list.


1 Answers

You can use the key option of the sort command, which takes a "field number", so if you wanted the second column:

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 
like image 67
Matt Ryall Avatar answered Sep 28 '22 18:09

Matt Ryall