Linux shell sort file according to second column?

I have a file like this:

FirstName, FamilyName, Address, PhoneNumber 

How can I sort it by last name?

+52
linux shell
Nov 24 '10 at 1:14
source share
4 answers

If it is UNIX:

 sort -k 2 file.txt 

You can use multiple -k flags to sort more than one column. For example, to sort by last name, and then first as a constraint constraint:

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

Relevant options from "man sort":

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

run the key in POS1, put it on POS2 (start 1)

POS - F [.C] [OPTS], where F is the field number and C is the character position in the field. OPTS is one or more one-letter order options that override the global order parameters for this key. If no key is specified, use the entire string as the key.

-t, --field-separator = SEP

use SEP instead of a non-empty null transition

+91
Nov 24 '10 at 1:19
source share

To sort only by the second field (if the second fields coincide, these lines coincide in the order in which they are in the original without sorting by other fields):

 sort -k 2,2 -s orig_file > sorted_file 
+5
May 30 '12 at 16:24
source share

sort -nk2 file.txt

Accordingly, you can change the column number.

+1
Jan 16 '16 at 19:29
source share

FWIW, here is a sorting method showing which processes use the most virtual memory.

 memstat | sort -k 1 -t':' -g -r | less 

Sorting options are set to the first column, using: as a column separator, numerical sorting and sorting in reverse order.

0
Dec 01 '16 at 16:37
source share



All Articles