Using sort
sort is a Unix command to order data in file(s) in a sequence.
Sort command output
Section titled “Sort command output”sort command is used to sort a list of lines.
Input from a file
sort file.txtInput from a command
You can sort any output command. In the example a list of file following a pattern.
find * -name pattern | sortMake output unique
Section titled “Make output unique”If each lines of the output need to be unique, add -u option.
To display owner of files in folder
ls -l | awk '{print $3}' | sort -uNumeric sort
Section titled “Numeric sort”Suppose we have this file:
test>>cat file10.Gryffindor4.Hogwarts2.Harry3.Dumbledore1.The sorting hatTo sort this file numerically, use sort with -n option:
test>>sort -n fileThis should sort the file as below:
1.The sorting hat2.Harry3.Dumbledore4.Hogwarts10.GryffindorReversing sort order: To reverse the order of the sort use the -r option
To reverse the sort order of the above file use:
sort -rn fileThis should sort the file as below:
10.Gryffindor4.Hogwarts3.Dumbledore2.Harry1.The sorting hatSort by keys
Section titled “Sort by keys”Suppose we have this file:
test>>cat Hogwarts Harry Malfoy Rowena Helga Gryffindor Slytherin Ravenclaw Hufflepuff Hermione Goyle Lockhart Tonks Ron Snape Olivander Newt Ron Goyle Flitwick SproutTo sort this file using a column as key use the k option:
test>>sort -k 2 HogwartsThis will sort the file with column 2 as the key:
Ron Goyle Flitwick Sprout Hermione Goyle Lockhart Tonks Harry Malfoy Rowena Helga Gryffindor Slytherin Ravenclaw Hufflepuff Ron Snape Olivander NewtNow if we have to sort the file with a secondary key along with the primary key use:
sort -k 2,2 -k 1,1 HogwartsThis will first sort the file with column 2 as primary key, and then sort the file with column 1 as secondary key:
Hermione Goyle Lockhart Tonks Ron Goyle Flitwick Sprout Harry Malfoy Rowena Helga Gryffindor Slytherin Ravenclaw Hufflepuff Ron Snape Olivander NewtIf we need to sort a file with more than 1 key , then for every -k option we need to specify where the sort ends. So -k1,1 means start the sort at the first column and end sort at first column.
-t option
In the previous example the file had the default delimeter - tab. In case of sorting a file that has non-default delimeter we need the -t option to specify the delimeter. Suppose we have the file as below:
test>>cat file5.|Gryffindor4.|Hogwarts2.|Harry3.|Dumbledore1.|The sorting hatTo sort this file as per the second column, use:
test>>sort -t "|" -k 2 fileThis will sort the file as below:
3.|Dumbledore5.|Gryffindor2.|Harry4.|Hogwarts1.|The sorting hatSyntax
Section titled “Syntax”- sort [option] filename
Parameters
Section titled “Parameters”| Option | Meaning |
|---|---|
| -u | Make each lines of output unique |
Remarks
Section titled “Remarks”Full user manual of sort reading online