linux(centos8):用uniq去除文本中重复的行(去重)

一,uniq命令的用途

1, 作用:

    从输入文件或标准输入中找到相邻的匹配行,

    并写入到输出文件或标准输出

2, 使用时通常会搭配sort使用

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,查看uniq命令所属的rpm包

[root@blog nginxlogs]$ whereis uniq
uniq: /usr/bin/uniq /usr/share/man/man1/uniq.1.gz /usr/share/man/man1p/uniq.1p.gz

[root@blog nginxlogs]$ rpm -qf /usr/bin/uniq
coreutils-8.30-6.el8.x86_64

默认已安装到了centos8系统,如果找不到命令或误删除,

可以用dnf来安装

[root@blog nginxlogs]$ dnf install coreutils

三,查看uniq的版本和帮助

1,查看版本

[root@blog nginxlogs]$ uniq --version
uniq (GNU coreutils) 8.30
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://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 Richard M. Stallman and David MacKenzie.

2,查看帮助

[root@blog nginxlogs]$ uniq --help

3,查看手册 

[root@blog nginxlogs]$ man uniq

四,uniq命令的使用例子

1,增加统计重复出现的次数

#-c: 增加显示当前行重复出现的次数

[root@blog nginxlogs]$ cut -d ' ' -f 1 file_meet.access_log | sort | uniq -c
      1 106.15.200.123
    875 223.72.53.168
      9 47.101.200.88
      9 47.101.58.46
...

当然可以加一个倒排

[root@blog nginxlogs]$ cut -d ' ' -f 1 file_meet.access_log | sort | uniq -c | sort -k1 -nr
    875 223.72.53.168
      9 47.101.58.46
      9 47.101.200.88
      1 106.15.200.123
...

2,只显示有重复的行

#-d: 只显示重复出现的行

[root@blog nginxlogs]$ cut -d ' ' -f 1 file_meet.access_log | sort | uniq -d
223.72.53.168
47.101.200.88
47.101.58.46
...

3,仅显示没有重复仅出现一次的行

#-u:uniqe

[root@blog nginxlogs]$ cut -d ' ' -f 1 file_meet.access_log | sort | uniq -u
106.15.200.123

4,其他参数:

-s: 指定在每行开始处需要忽略的字符数

-i:  忽略每行字母的大小写

五,uniq命令使用需要注意的地方:

如果重复的行不相邻,uniq 命令不会起作用

所以通常我们会搭配sort命令使用,先排序,使重复的行相邻出现,

这样uniq命令就可以生效了

六,查看centos的版本

[root@blog nginxlogs]$ cat /etc/redhat-release
CentOS Linux release 8.0.1905 (Core) 
原文地址:https://www.cnblogs.com/architectforest/p/12893339.html