Hack 23. Sort Command Examples

by Ramesh

Sort command sorts the lines of a text file. Following are several practical examples on how to use the sort command based on the following sample text file that has employee information in the format:

  1. employee_name:employee_id:department_name.
  1. $ cat names.txt
  2.  
  3. Emma Thomas:100:Marketing
  4. Alex Jason:200:Sales
  5. Madison Randy:300:Product Development
  6. Sanjay Gupta:400:Support
  7. Nisha Singh:500:Sales

Sort a text file in ascending order

  1. $ sort names.txt
  2.  
  3. Alex Jason:200:Sales
  4. Emma Thomas:100:Marketing
  5. Madison Randy:300:Product Development
  6. Nisha Singh:500:Sales
  7. Sanjay Gupta:400:Support

Sort a text file in descending order

  1. $ sort -r names.txt
  2.  
  3. Sanjay Gupta:400:Support
  4. Nisha Singh:500:Sales
  5. Madison Randy:300:Product Development
  6. Emma Thomas:100:Marketing
  7. Alex Jason:200:Sales

Sort a colon delimited text file on 2nd field (employee_id)

  1. $ sort -t: -k 2 names.txt
  2.  
  3. Emma Thomas:100:Marketing
  4. Alex Jason:200:Sales
  5. Madison Randy:300:Product Development
  6. Sanjay Gupta:400:Support
  7. Nisha Singh:500:Sales

Sort a tab delimited text file on 3rd field (department_name) and suppress duplicates

  1. $ sort -t: -u -k 3 names.txt
  2.  
  3. Emma Thomas:100:Marketing
  4. Madison Randy:300:Product Development
  5. Alex Jason:200:Sales
  6. Sanjay Gupta:400:Support

Sort the passwd file by the 3rd field (numeric userid)

  1. $ sort -t: -k 3n /etc/passwd | more
  2.  
  3. root:x:0:0:root:/root:/bin/bash
  4. bin:x:1:1:bin:/bin:/sbin/nologin
  5. daemon:x:2:2:daemon:/sbin:/sbin/nologin
  6. adm:x:3:4:adm:/var/adm:/sbin/nologin
  7. lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

Sort /etc/hosts file by ip-address

  1. $ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /etc/hosts
  2.  
  3. 127.0.0.1 localhost.localdomain localhost
  4. 192.168.100.101 dev-db.thegeekstuff.com dev-db
  5. 192.168.100.102 prod-db.thegeekstuff.com prod-db
  6. 192.168.101.20 dev-web.thegeekstuff.com dev-web
  7. 192.168.101.21 prod-web.thegeekstuff.com prod-web

Combine sort with other commands

  • ps –ef | sort : Sort the output of process list
  • ls -al | sort +4n : List the files in the ascending order of the file-size. i.e sorted by 5th filed and displaying smallest files first.
  • ls -al | sort +4nr : List the files in the descending order of the file-size. i.e sorted by 5th filed and displaying largest files first.