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
|