Shell之sort与uniq命令简介
一、sort命令使用
1. 指定按数字排序:
[root@TopInsight sort]#cat file1
paixu 4
hebing 1
weiyi 2
chongfu 3
[root@TopInsight sort]#sort -n file1
chongfu 3
hebing 1
paixu 4
weiyi 2
2.逆序排序:
[root@TopInsight sort]#sort -nr file1
weiyi 2
paixu 4
hebing 1
chongfu 3
3.检查是否已经排序:
[root@TopInsight sort]#cat file2
5
6
7
8
[root@TopInsight sort]#sort -c file1
sort:file1:2:无序: hebing 1
4.检查是否按照数字排序:
[root@TopInsight sort]#sort -cn file2
5.合并两个文件,并对结果进行排序:
[root@TopInsight sort]#sort -m file1 file2 | sort
5
6
7
8
chongfu 3
hebing 1
paixu 4
weiyi 2
6.按照键或者列进行排序(默认列与列之间按照空格分开):
[root@TopInsight sort]#cat file3
paixu 4
hebing 1
weiyi 2
chongfu 3
5
6
7
8
7.指定第二列(-k选项),按数字逆序排序
[root@TopInsight sort]#sort -nrk 2 file3
paixu 4
chongfu 3
weiyi 2
hebing 1
8
7
6
5
8.指定非空格作为分隔符(-t选项):
[root@TopInsight sort]#cat file4
paixu,4
hebing,1
weiyi,2
chongfu,3
5
6
7
8
[root@TopInsight sort]#sort -t ',' -nrk 2 file4
paixu,4
chongfu,3
weiyi,2
hebing,1
8
7
6
5
9.指定先按第2列,再按第三列排序(复合排序):
[root@TopInsight sort]#cat data.txt
1 hellomy txt
1 hellomy ami
2 myname is
3 you are
4 nihao
5 amao
[root@TopInsight sort]#sort -nk 2,3 data.txt
1 hellomy ami
1 hellomy txt
2 myname is
3 you are
4 nihao
5 amao
10.忽略文件中的空白符号(-b选项):
[root@TopInsight sort]#cat data2.txt
1 hellomy txt
2 myname is
4 nihao
5 amao
1 hellomy ami
3 you are
[root@TopInsight sort]#sort -bnk 2,3 data2.txt
1 hellomy ami
1 hellomy txt
2 myname is
3 you are
4 nihao
5 amao
11.使用sort的结果作为xargs的参数时候,注意与find命令一样需要指定字符串终止符(\0)
[root@TopInsight sort]#sort -nrk 2 file3 -z | xargs -0 echo
paixu 4
hebing 1
weiyi 2
chongfu 3
5
6
7
8
二、uniq命令的用法
uniq命令用于对排序过的文件进行去重操作:
1.排序后去重
[root@TopInsight sort]#cat data3.txt
root
root
hx
hx
root
foolson
man
man
honghong
longlong
first
second
[root@TopInsight sort]#sort data3.txt | uniq
first
foolson
honghong
hx
longlong
man
root
second
或者:
[root@TopInsight sort]#sort -u data3.txt
first
foolson
honghong
hx
longlong
man
root
second
2.只显示没有重复的行:
[root@TopInsight sort]#sort data3.txt | uniq -u
first
foolson
honghong
longlong
second
3.找出重复的行:
[root@TopInsight sort]#sort data3.txt | uniq -d
hx
man
root
三、使用实例
1.实例1:
列出一个字符串包含的每个字符的个数:
[root@TopInsight sort]#echo aaBBCCCaaccddabd | sed 's/[^.]/&\n/g' | sed '/^$/d' | sort -f | uniq -c
5 a
1 b
2 B
2 c
3 C
3 d
2.实例2:
依据apache日志,找出访问ip,按照访问日志数排序:
[root@TopInsight sort]#sort /var/log/httpd/access_log | cut -f 1 -d " " | uniq -c | sort -r
24 191.255.255.254
21 ::1