首頁·終端機命令

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