约 5045 字

约 25 分钟

#Bash 的 uniq 命令

uniq [OPTION]... [INPUT [OUTPUT]]

功能

过滤文件中连续的重复行。

类型

可执行文件(/usr/bin/uniq),属于 coreutils。

参数

  • OPTION 选项:
    • -c, --count - 按出现的次数给行添加前缀
    • -d, --repeated - 仅打印重复的行一次
    • -D - 打印所有重复行
    • --all-repeated[=METHOD] - 打印所有重复行,并使用空行分隔分组:
      • none - 不使用空行分隔分组;同 -D(默认)
      • prepend - 每组之前空行
      • separate - 两组之间空行
    • -f, --skip-fields=N - 避免比较前 N 个字段
    • --group[=METHOD] - 打印所有行,并使用空行分组
      • separate - 两组之间空行
      • prepend - 每组之前空行
      • append - 每组之后空行
      • both - 每组前后空行
    • -i, --ignore-case - 忽略大小写
    • -s, --skip-chars=N - 不比较行的前 N 个字符
    • -u, --unique - 仅打印唯一的行
    • -z, --zero-terminated - 以空字符(\0)作为行的结尾,而不是换行符(\n)
    • -w, --check-chars=N - 只比较行的前 N 个字符
    • --help - 显示帮助
    • --version - 显示版本
  • INPUT - 输入文件;如果没有这个参数或指定为 -,则从标准输入读取
  • OUTPUT - 输出文件;如果没有这个参数或指定为 -,则打印到标准输出

#示例

$ cat 1.txt
Primers 编程伙伴
Primers 编程伙伴
https://xplanc.org/primers/
https://xplanc.org/primers/
Primers 编程伙伴
Primers 编程伙伴
https://xplanc.org/primers/
https://xplanc.org/primers/
Primers 编程伙伴 https://xplanc.org/primers/
$ uniq 1.txt                                    # 过滤连续的重复行
Primers 编程伙伴
https://xplanc.org/primers/
Primers 编程伙伴
https://xplanc.org/primers/
Primers 编程伙伴 https://xplanc.org/primers/
$ uniq -c 1.txt                                 # 打印重复次数
      2 Primers 编程伙伴
      2 https://xplanc.org/primers/
      2 Primers 编程伙伴
      2 https://xplanc.org/primers/
      1 Primers 编程伙伴 https://xplanc.org/primers/
$ uniq -d 1.txt                                 # 仅打印连续的重复行一次
Primers 编程伙伴
https://xplanc.org/primers/
Primers 编程伙伴
https://xplanc.org/primers/
$ uniq -D 1.txt                                 # 仅打印所有重复行
Primers 编程伙伴
Primers 编程伙伴
https://xplanc.org/primers/
https://xplanc.org/primers/
Primers 编程伙伴
Primers 编程伙伴
https://xplanc.org/primers/
https://xplanc.org/primers/
$ uniq -u 1.txt                                 # 仅打印唯一行
Primers 编程伙伴 https://xplanc.org/primers/

#推荐阅读

#手册

更新: 2026/1/18

作者: PlanC

创建: 2025/12/5