sort - sort lines of text files(對文本文件的行進行排序)
sort將文件的每一行作為一個單位,相互比較,比較原則是從首字符向后,依次按ASCII碼值進行比較,最后將它們按升序輸出。
格式:
sort [OPTION]... [FILE]...
OPTION:
- -u,--unique :去重
- -r,--reverse :降序排列,不加sort命令默認升序
- -o, --output=FILE :將排序結果保存至文件中,也可使用重定向工具
- -n, --numeric-sort :根據數值排序
- -t, --field-separator=SEP :指定特定分隔符,默認以空格為分隔符。與cut -d一樣一樣的
- -k, --key=KEYDEF :指定特定列做為排序,默認忽略開頭空白字符。與cut -f一樣一樣的。
- -M, --month-sort :根據月份進行排序,支持英文縮寫格式:Jan
- -b, --ignore-leading-blanks :忽略每一行前面的所有空白部分,從第一個可見字符開始比較
- -f, --ignore-case :忽略大小寫
示例:
$ awk -F'|' '{print $2}' nginx_access.log | uniq -c | sort -n -r | head -n 10 #查詢訪問次數前10的ip地址。uniq -c 表示統計各行在文件中出現的次數
2582 120.26.40.76
826 120.26.40.76
716 120.26.40.76
525 120.26.40.76
424 120.26.40.76
325 120.26.40.76
235 120.26.40.76
233 120.26.40.76
226 120.26.40.76
120 120.26.40.76
uniq - report or omit repeated lines(報告或省略重復的行)
描述:
uniq 命令刪除文件中的重復行。uniq 命令讀取由 InFile 參數指定的標准輸入或文件。該命令首先比較相鄰的行,然后除去第二行和該行的后續副本。重復的行一定相鄰。(在發出 uniq 命令之前,請使用 sort 命令使所有重復行相鄰。uniq命令這種方式估計是想節省系統資源)最后,uniq 命令將最終單獨的行寫到標准輸出或由 OutFile 參數指定的文件。InFile 和 OutFile 參數必須指定不同的文件。
格式:
uniq [OPTION]... [InFile [OutFile]]
OPTION:
- -c :在輸出行前面加上每行在文件中出現的次數
- -d :僅顯示重復行
- -u :僅顯示不重復的行
示例:
$ cat fruit.txt
apple
banana
orange
apple
$ uniq fruit.txt #可以看到apple不是鄰近的,所以無法去重
apple
banana
orange
apple
$ uniq -d fruit.txt
$
$ sort fruit.txt #先排序,將相同的行安排在一起
apple
apple
banana
orange
$ sort fruit.txt | uniq #排序后,去重
apple
banana
orange
$ awk -F'|' '{print $2}'nginx_access.log | sort -n |uniq -c | sort -n | tail -n 10 #只有先sort后在uniq才能生效
28 122.192.13.58
31 183.212.188.57
31 223.104.4.82
35 223.104.4.61
36 112.20.81.240
71 183.209.48.38
86 122.96.43.243
216 183.208.16.53
616 49.77.231.174
6268 120.26.40.76
總結:
uniq
必須得和sort
一起使用才能夠達到所需要的結果。