Linux秘笈23.Sort命令
三月 5th, 2009 Posted in Linux
Sort命令能够对一个文本文件的行进行排序,下面的几个实用的样例展示怎么去对样例文本进行排序。样例文本的格式为:employee_name:employee_id:department_name.
$ cat names.txt Emma Thomas:100:Marketing Alex Jason:200:Sales Madison Randy:300:Product Development Sanjay Gupta:400:Support Nisha Singh:500:Sales |
以一个升序排列文本文件
$ sort names.txt Alex Jason:200:Sales Emma Thomas:100:Marketing Madison Randy:300:Product Development Nisha Singh:500:Sales Sanjay Gupta:400:Support |
以倒序排列文本文件
$ 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
用第二字段排列一个以冒号分隔的文本文件
$ 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 |
以第三个字段排列一个以tab分隔的文本文件,并且禁止重复
$ sort -t: -u -k 3 names.txt Emma Thomas:100:Marketing adison Randy:300:Product Development Alex Jason:200:Sales Sanjay Gupta:400:Support |
通过ip地址来排序/etc/hosts文件
$ sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n /etc/hosts 127.0.0.1 localhost.localdomain localhost 192.168.100.101 dev-db.thegeekstuff.com dev-db 192.168.100.102 prod-db.thegeekstuff.com prod-db 192.168.101.20 dev-web.thegeekstuff.com dev-web 192.168.101.21 prod-web.thegeekstuff.com prod-web |
合并sort和其他命令
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. |
