linux(centos8):用sort對文本內容排序


一,sort的用途 

1,作用:

sort命令用於將文本文件內容加以排序。

它能夠以行為單位來排序

 

2,sort常與uniq搭配使用,原因:

     用uniq命令去重時,

     需要相同的每行位置相鄰才能生效,

     所以通常要在uniq之前先用sort做排序 

     而在uniq做統計之后,通常也會根據重復次數做排序,

    這種情況下也會用到uniq

 

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,查看sort命令所屬的包

[root@blog ~]$ whereis sort
sort: /bin/sort /usr/share/man/man1p/sort.1p.gz /usr/share/man/man3/sort.3pm.gz /usr/share/man/man1/sort.1.gz

[root@blog ~]$ rpm -qf /bin/sort
coreutils-8.4-31.el6_5.2.x86_64

 

如果提示找不到命令或命令被誤刪除,

可以用dnf安裝

[root@blog ~]$ dnf install coreutils

 

三,查看sort命令的版本和幫助

1,查看版本

[root@loadserver ~]$ sort --version
sort (GNU coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and Paul Eggert.

 

2,查看幫助

[root@loadserver ~]$ sort --help

 

3,查看手冊 

[root@loadserver ~]$ man sort

 

四,sort命令在運維工作中的例子

1,統計404的url

#-n: --numeric-sort    按照數字的值進行比較

#-k:--key=POS1[,POS2]     start a key at POS1 (origin 1), end it at POS2

        按指定的列做排序

#-r:--reverse    反序排列

[root@blog nginxlogs]$ awk '$9==404{print $7}' ilc_ssl.access.log | sort | uniq -c | sort -k1 -nr
     73 /robots.txt
     37 /apple-touch-icon.png
     ...

 

2,統計404的ip的出現次數

[root@blog nginxlogs]$ awk '$9==404{print $1}' ilc_ssl.access.log | sort | uniq -c | sort -k1 -nr
     10 61.152.68.150
      9 156.229.7.2
        ...

 

3,對系統中的用戶按uid做倒序排列:

#-t:指定排序用的字段的分隔符

[root@blog ~]$ sort -t ":" -k 3 -nr /etc/passwd

 

4,對排序結果去重

例子:打印所有引發404的ip,按ip排序並去除重復

#-u: 去除重復

[root@blog nginxlogs]$ awk '$9==404{print $1}' ilc_ssl.access.log | sort -t ' ' -u 

說明:sort的去重不具備uniq統計次數的功能

 

5,按兩個字段做排序:

-k7   : 按第七列正序排列

-k3nr :按第三列以數值倒序排列

[root@blog ~]# sort -t: -k7 -k3nr /etc/passwd

 

6,按指定的字符做排序:

按第一列的第1個到第3個字符做排序

[root@blog ~]# sort -t: -k1.1,1.3 /etc/passwd

 

六,查看centos的版本

[root@blog ~]$ cat /etc/redhat-release
CentOS Linux release 8.0.1905 (Core) 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM