Untitled Document
sort Command

sort - command orders data in ascending or descending sequence .The sort command orders a file. By default , sort reorders lines in ASCII collating sequence - whitespace first, then numerals , uppercase , letters and finally lowercase letters .This default sorting sequence can be altered by using certain options . We can also sort on one or more keys ( fields) or use a different ordering rule .

Example 1 - Basic Example

Run the following sort command ,to sort emp.csv file .

   sort emp.csv       

Example 2 Sorting files based on fields (-k) option

We will be using the -k ( keys ) option to identify keys (the fields) . We have already seen the field separator like space , comma , pipe | etc. here also we will use -t option to specify the delimiter .

Below example will sort on the second field ( name) so the option sholud be -k 2 .

   sort -t "," -k 2 emp.csv     

Example 3 - Reversing the sort order , the (-r) option .

The sort order can be reversed with (-r) option . The following sequence reverses a sequence of previous sorting order.

   sort -t "," -r -k 2 emp.csv OR 
   sort -t "," -k 2r emp.csv  ------------------- An alternative way to above synatx 

Example 4 - Sorting on secondary key -

We can sort on more than one key i.e we can provide a secondary key to sort . If the primary key is the third field and the secondary key is the second field , then we need to specify for every -k option , where the sort ends .

  sort -t "," -k 3,3 -k 2,2 emp.csv 

Example 5 - Sorting on columns

We can also specify a character position within a field to be the begining of sort .If you have to sort the file according to the year of birth , then we need to sort on the seventh and eight column position within the fifth field .

  sort -t "," -k 5.7,5.8 emp.csv

Example 6 - Numeric Sort (-n) option

When sort acts on numerals , strange things can happen . When we sort a file containing only numbers , we get strange results .Hence use sort with -n option .

  sort -n emp.csv 

Example 7 - Removing Repeated Lines (-u) option

The -u ( unique) option lets you remove repeated lines froma file . Below example prints only unique employee names from emp.csv

  cut -d "," -f3 emp.csv | sort -u 

Example 8 - Redirecting output to a file (-o) option

Even though sort's output can be redirected to a file, we can use its -o otpion to specify the output filename

  sort -o emp.csv -k 2 list --------------------------- Output stored in file name list  

Example 9 - (-c) check otpion , to check whether file is sorted or not

The -c ( check) option check whether the file has actually been sorted in the default order , use the -c ( check) option

  sort -c list 
  $_             --------------------------- File is sorted 

Example 10 - (-m) merge otpion , to merge two or more files

The -m ( merge ) option can merge two or more files

  sort -m list emp.csv shortlist  
Untitled Document