sort用于排序,可以根据不同的数据类型来进行排序,例如想要查看最后一个登陆的用户信息,可以把last和sort结合起来使用,按照登陆时间排序。
使用sort排序:
sort常用参数:
-f :忽略大小写的差异
-b:忽略最前面的空格符部分
-M:以月份的名字排序
-n:使用纯数字排序(默认为以文字类型排序)
-r:反向排序
-u:去除重复行,重复的数据只显示一次
-t:分隔符,默认为tab为分隔符
-k:以哪个区间来排序
1 2 3 4 5 6 7 8 9 10 11 12 | [whx@localhost test ]$ last | sort reboot system boot 2.6.32-696.el6.x MonAug 21 19:42 - 03:22 (07:40) reboot system boot 2.6.32-696.el6.x SunAug 20 22:50 - 03:08 (04:17) reboot system boot 2.6.32-696.el6.x ThuAug 17 18:38 - 02:57 (08:18) reboot system boot 2.6.32-696.el6.x ThuJul 20 03:25 - 18:03 (14:37) reboot system boot 2.6.32-696.el6.x WedAug 23 01:17 - 03:15 (01:57) reboot system boot 2.6.32-696.el6.x WedAug 23 18:15 - 20:14 (01:58) reboot system boot 2.6.32-696.el6.x WedJul 19 09:39 - 03:24 (17:45) whx pts /0 :0.0 Thu Aug 17 18:40 - 02:57 (08:16) whx pts /0 :0.0 Thu Jul 20 03:23 - down (00:01) ... |
以:为分隔符,以第4区间按照数字排序:
1 2 3 4 5 6 7 8 9 10 | [whx@localhost test ]$ cat /etc/passwd | sort -t ':' -k 4 -n halt:x:7:0:halt: /sbin : /sbin/halt operator:x:11:0:operator: /root : /sbin/nologin root:x:0:0:root: /root : /bin/bash shutdown :x:6:0: shutdown : /sbin : /sbin/shutdown sync :x:5:0: sync : /sbin : /bin/sync 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 |
使用sort排序并去除重复数据:
1 2 3 4 5 | [whx@localhost test ]$ last | cut -d ' ' -f 1 | sort -u reboot whx wtmp |
也可以用uniq来去除重复数据:
1 2 3 4 5 | [whx@localhost test ]$ last | cut -d ' ' -f1 | sort | uniq reboot whx wtmp |
uniq 的作用是将重复行去重,使得显示出来的每一行都是唯一的,配合参数也可以只查看文件中有哪些重复的行,重复次数是多少,例如查看每个用户的登陆总次数。
参数:
-c:统计次数
-i:忽略大小写
-d:列出重复的行
-u:列出不重复的行
使用sort排序并去除重复数据,统计出现次数:
1 2 3 4 | [whx@localhost test ]$ uniq -c . /test .txt 3 > test test def def def acb 2 > test1 test def def def acb 1 > test1 test def def def ac |
查看每个用户的登陆总次数:
1 2 3 4 5 | [whx@localhost test ]$ last | cut -d ' ' -f1 | sort | uniq -c 1 7 reboot 25 whx 1 wtmp |
不添加参数(列出文件中行,重复的行只显示一次)
1 2 3 4 | [whx@localhost test ]$ uniq . /test .txt > test test def def def acb > test1 test def def def acb > test1 test def def def ac |
使用-d参数列出重复行,每个重复的行显示一次;
1 2 3 | [whx@localhost test ]$ uniq -d . /test .txt > test test def def def acb > test1 test def def def acb |
使用-u参数列出不重复的行
1 2 | [whx@localhost test ]$ uniq -u . /test .txt > test1 test def def def ac |
wc用于统计文件行数,字数,字符数等信息。
参数:
-l:仅列出行数量
-w:仅列出字数量
-m:仅列出字符数量
统计last的行数,字数,字符数:
1 2 | [whx@localhost test ]$ last | wc 34 334 2502 -- 依次代表行数,字数,字符数 |
查看test.txt的行数,字数,字符数:
1 2 | [whx@localhost test ]$ wc . /test .txt 6 42 183 . /test .txt |
查看test.txt的字节数:
1 2 | [whx@localhost test ]$ wc -c . /test .txt 183 . /test .txt
|
本文转自 天黑顺路 51CTO博客,原文链接:http://blog.51cto.com/mjal01/1959008,如需转载请自行联系原作者