linux数据排序神器sort
学运维及大数据的,一定要熟练运用sort命令
比如:需要统计网站哪一个页面的访问量多,将访问多的网站分配多的服务器资源
# sort 是排序的意思
# 主要用于排序文件、对已排序的文件进行合并,并检查文件以确定它们是否已排序
# sort有三种模式,(牢记)
1.排序模式 默认
2.合并模式 (-m)对两个已排序的文件进行合并 ,注意是已排序,也可以通过参数指定那一列是已排序 -k2 是第二列
3.检查模式 (-c)测试给定的输入文件是否已排序,未排序输出未排序的第一行,已排序不输出
# 默认情况下,sort将所有字符视为字符串。数字字符也被视为字符
# 而字符默认是以ascii编码,但又有些不一样
[root@hecs-98663 shell]# sort c
ABC
BNM
ewr
fsd
hjk
HJK
IO
RTY
wqe
# 26个单词从小到大排序,如果是同字母,大写排在小写前面
学习参数
# 如果遇到以数字排序的文件 使用-n (number)
[root@hecs-98663 shell]# sort num
01
10
111
25
502
83
[root@hecs-98663 shell]# sort -n num
01
10
25
83
111
502
# 反转排序用-r
[root@hecs-98663 shell]# sort -nr num
502
111
83
25
10
01
------------------------------------------------------------
# sort 与uniq 结合可以解决工作中大部分问题
[root@hecs-98663 shell]# sort -n num | wc -l
89
# 删除重复的行
[root@hecs-98663 shell]# sort -n num | uniq
11
22
33
44
77
3311
# 统计重复行的次数
[root@hecs-98663 shell]# sort -n num | uniq -c
1 11
22 22
23 33
22 44
11 77
10 3311
# 使用次数由低到高再排一下序
[root@hecs-98663 shell]# sort -n num | uniq -c | sort -n
1 11
10 3311
11 77
22 22
22 44
23 33
-------------------------------------------------------------
# 删除重复行 -u uniq
# 作用:可以统计今天有多少用户浏览网站
[root@hecs-98663 shell]# sort -u num
11
22
33
3311
44
77
# 单词有大小写之分,忽略大小写 -f
[root@hecs-98663 shell]# sort -u word
hello
Hello
world
woRld
[root@hecs-98663 shell]# sort -u -f word
hello
world
# 按列排序 -k k2表示第二列
[root@hecs-98663 shell]# sort -k2 people
Youth 400 England
Kids 500 India
Senior 600 USA
Pensioners 650 China
Junior 9000 Australia
# 多列进行排序
[root@localhost test]# sort -k1,1 -k2,2n -k3,3n columns.txt
version1.1 5 8
version1.1 10 20
version1.1 10 30
version1.1 40 50
version1.2 10 25
version1.2 30 50
version1.2 40 50
# 分隔符 -t
[root@localhost test]# sort -n -t ':' -k3 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
news:x:9:13:news:/etc/news:
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
<---output truncated--->
# 按月排序 -M
[root@localhost test]# sort -M months.txt
jan
feb
may
july
august
sep
dec
#人类可读的数字进行排序 -h
[root@localhost test]# sort -h human_numeric.txt
2K
34K
3M
52M
200M
1G
4G

浙公网安备 33010602011771号