首页·终端命令

uniq

文本处理

用法

sort [file] | uniq -c

只把相邻的重复行合成一行,看不到散落各处的重复,所以几乎总是接在 sort 之后。

常用选项

选项含义
-cPrefix each line with how many times it repeated
-dOnly the lines that appear more than once
-uOnly the lines that appear exactly once
-iIgnore case
-fSkip the first N fields before comparing

示例

sort access.log | uniq -c | sort -rn | head

The most repeated lines.

uniq -d list.txt

Just the duplicates.

它们本来就是用管道串起来用的。串三条往往比让一条命令做完所有事更短。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. uniq 是做什么的?

只把相邻的重复行合成一行,看不到散落各处的重复,所以几乎总是接在 sort 之后。

Q. 怎么写?

sort [file] | uniq -c —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 5 个,完整列表在 man uniq。这条命令属于文本处理。

相关命令

man 手册: man uniq