sort | uniq -c:正确统计重复行

用 uniq -c 统计 Linux 日志中的重复行并排序,注意输入必须先排序。

Linuxuniq 去重重复文件sort 排序低风险
执行 sort 文件 | uniq -c 即可在每行前加上出现次数,再用 sort -rn 按次数排名。

01命令

命令
$ sort access.log | uniq -c | sort -rn | head

02作用说明

uniq 最容易被忽略的前提是它只比较相邻行——前面不加 sort,散落在文件各处的重复内容根本检测不到。-c 让每行输出带上次数列,-d 只显示重复行,-u 只显示唯一行,-i 忽略大小写。经典的“出现频率最高的行”写法就是 sort | uniq -c | sort -rn,从热门 IP 列表到热门 URL 统计都靠它。

03风险

风险低风险
!注意: uniq 永远发现不了不相邻的重复——必须先 sort,否则统计结果是错的。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • uniq(1) — Arch Linux manual
    Arch Linux · technical · 2026-09-17
    依据: -c prefixes the number of occurrences; documents that uniq only compares adjacent equal lines
  • uniq(1P) — POSIX manual page
    man7.org · technical · 2026-09-17
    依据: POSIX specifies that input must be sorted for uniq to detect all repeated lines

最后验证: 2026-09-17 · 分类: 文件与文件夹