Original article address:
- Basic
- Common commands
The sort command can sort text lines in a file. The following examples demonstrate how to use the sort command. The example is employee data in the format of: employee_name: employee_id: department_name.
Root@hexu.org ~ #Cat names.txt
Emma Thomas: 100: Marketing
Alex Jason: 200: Sales
Madison RANDY: 300: Product Development
Sanjay Gupta: 400: Support
Nisha Singh: 500: Sales
1) Sort text in ascending order
Root@hexu.org ~ #Sort names.txt
Alex Jason: 200: Sales
Emma Thomas: 100: Marketing
Madison RANDY: 300: Product Development
Nisha Singh: 500: Sales
Sanjay Gupta: 400: Support
2) Sort text in descending order
Root@hexu.org ~ #Sort-r names.txt
Sanjay Gupta: 400: Support
Nisha Singh: 500: Sales
Madison RANDY: 300: Product Development
Emma Thomas: 100: Marketing
Alex Jason: 200: Sales
3) sort the second entry of a file separated by colons (that is, employee_id)
Root@hexu.org ~ #Sort-T:-K 2 names.txt
Emma Thomas: 100: Marketing
Alex Jason: 200: Sales
Madison RANDY: 300: Product Development
Sanjay Gupta: 400: Support
Nisha Singh: 500: Sales
4) sort the third item separated by tab (department_id) and remove duplicate items
Root@hexu.org ~ #Sort-T:-u-k 3 names.txt
Emma Thomas: 100: Marketing
Madison RANDY: 300: Product Development
Alex Jason: 200: Sales
Sanjay Gupta: 400: Support
5) sort the third item of the passwd file (userid)
Root@hexu.org ~ #Sort-T:-K 3n/etc/passwd | more
Root: X: 0: 0: Root:/root:/bin/bash
Bin: X: 1: 1: Bin:/bin:/sbin/nologin
Daemon: X: 2: 2: daemon:/sbin/nologin
ADM: X: 3: 4: ADM:/var/adm:/sbin/nologin
LP: X: 4: 7: LP:/var/spool/lpd:/sbin/nologin
6) Sort/etc/hosts files based on IP addresses
Root@hexu.org ~ #Sort-T.-K 1, 1N-K 2, 2n-K 3, 3n-K 4, 4N/etc/hosts
127.0.0.1 localhost. localdomain localhost
Dev-db.thegeekstuff.com 192.168.100.101 Dev-DB
192.168.100.102 prod-db.thegeekstuff.com prod-DB
192.168.101.20dev-web.thegeekstuff.com Dev-Web
192.168.101.21 prod-web.thegeekstuff.com prod-Web
7) used together with other commands
Root@hexu.org ~ #PS-Ef | sortSort the Process List
Root@hexu.org ~ #Ls-Al | sort + 4nSort LS-Al output in ascending order by file size (5th items)
Root@hexu.org ~ #Ls-Al | sort + 4nrSort LS-Al output in descending order by file size (5th items)
Query the last 10 rows of data in descending order by row number
Cat-N/var/log/test. log | grep "Wix" | tail-10 | sort-R
End