sort和uniq命令
sort命令主要是给给定的文档排序
测试文件:
Thomas:100:Marketing Alex Jason:200:Sales Blex Jason:200:Sales Madison Randy:300:Product Development Sanjay Gupta:400:Support Nisha Singh:500:Sales
默认的排序是正序,将每一个行看作一个整体
[root@Server1 Documents]# sort emp.txt Alex Jason:200:Sales Blex Jason:200:Sales Madison Randy:300:Product Development Nisha Singh:500:Sales Sanjay Gupta:400:Support Thomas:100:Marketing
-r 可以倒序排
[root@Server1 Documents]# sort -r emp.txt Thomas:100:Marketing Sanjay Gupta:400:Support Nisha Singh:500:Sales Madison Randy:300:Product Development Blex Jason:200:Sales Alex Jason:200:Sales
还可以指定一个分隔符将每行划分成多列,然后按某列进行排序
-t 执行特定的分隔符 –k 指定按那列进行排序
[root@Server1 Documents]# sort -t: -k 3 emp.txt Thomas:100:Marketing Madison Randy:300:Product Development Alex Jason:200:Sales Blex Jason:200:Sales Nisha Singh:500:Sales Sanjay Gupta:400:Support
第二列是数值类型,如果我们想按第2列排序,需要显示的指定按数值排序
[root@Server1 Documents]# sort -t: -k 2n emp.txt -r Thomas:100:Marketing Blex Jason:200:Sales Alex Jason:200:Sales Madison Randy:300:Product Development Sanjay Gupta:400:Support Nisha Singh:500:Sales
当某列出现重复的值时,我们可以使用-u选项来只显示第一次出现的值
[root@Server1 Documents]# sort -t: -k 2n emp.txt -r -u Thomas:100:Marketing Alex Jason:200:Sales Madison Randy:300:Product Development Sanjay Gupta:400:Support Nisha Singh:500:Sales
第二列“200“有两行,由于使用了-u选项只显现了第一次出现的行数据。
-o 可以将排序的结果存储到指定的文件里
[root@Server1 Documents]# sort -t: -k 2n emp.txt -r -u -o result [root@Server1 Documents]# more result Thomas:100:Marketing Alex Jason:200:Sales Madison Randy:300:Product Development Sanjay Gupta:400:Support Nisha Singh:500:Sales
-r可以倒序排,同时可以应用到指定列上。例如第二列按正序排,第三列按倒序排
[root@Server1 Documents]# sort -t: -k 2n -k 1r emp.txt Thomas:100:Marketing Blex Jason:200:Sales Alex Jason:200:Sales Madison Randy:300:Product Development Sanjay Gupta:400:Support Nisha Singh:500:Sales
uniq命令主要用来屏蔽重复行,该命令由于默认只检测相邻行,所以必须先进行排序再去重才有意义。
测试文件
[root@Server1 Documents]# more names.txt tom jack tom lily sue tom john
如果直接使用uniq:
[root@Server1 Documents]# uniq names.txt tom jack tom lily sue tom john
由于相邻没有重复的,所以原样输出。
和sort命令配合使用:
[root@Server1 Documents]# sort names.txt | uniq jack john lily sue tom
-c 可以输出每行重复了几次
[root@Server1 Documents]# sort names.txt | uniq -c
1 jack
1 john
1 lily
1 sue
3 tom
-d 只输出有重复的行
[root@Server1 Documents]# sort names.txt | uniq -c -d
3 tom
-u 只输出没有重复的行
[root@Server1 Documents]# sort names.txt | uniq -c -u
1 jack
1 john
1 lily
1 sue
-i 比较是否重复时忽略大小写