Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell sort file according to the second column?

Tags:

linux

shell

I have a file like this:

FirstName, FamilyName, Address, PhoneNumber

How can I sort it by FamilyName?

like image 455
Rami Jarrar Avatar asked Nov 24 '10 01:11

Rami Jarrar


People also ask

How do I sort a column according to 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 columns in bash?

Sort Command Options You can use the following options in conjunction with the raw command to modify how the values are sorted. -n – sorts in numerical values. -R – sort in random order but group the identical keys. -r – sort the values in reverse (descending order).


2 Answers

If this is UNIX:

sort -k 2 file.txt 

You can use multiple -k flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

sort -k 2,2 -k 1,1 file.txt 

Relevant options from "man sort":

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

like image 76
John Kugelman Avatar answered Oct 06 '22 13:10

John Kugelman


To sort by second field only (thus where second fields match, those lines with matches remain in the order they are in the original without sorting on other fields) :

sort -k 2,2 -s orig_file > sorted_file
like image 38
Cian Avatar answered Oct 06 '22 11:10

Cian