Linux shell sort file according to the second column?

LinuxShell

Linux Problem Overview


I have a file like this:

FirstName, FamilyName, Address, PhoneNumber

How can I sort it by FamilyName?

Linux Solutions


Solution 1 - Linux

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 >

Solution 2 - Linux

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

Solution 3 - Linux

sort -nk2 file.txt

Accordingly you can change column number.

Solution 4 - Linux

FWIW, here is a sort method for showing which processes are using the most virt memory.

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

Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRami JarrarView Question on Stackoverflow
Solution 1 - LinuxJohn KugelmanView Answer on Stackoverflow
Solution 2 - LinuxCianView Answer on Stackoverflow
Solution 3 - LinuxDheeraj KumarView Answer on Stackoverflow
Solution 4 - LinuxnetskinkView Answer on Stackoverflow