Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux Shell 文本處理利器 uniq 命令全解析:去重、計數、字段忽略與實戰案例

編輯:Linux 教學

定位:uniq — 針對「連續重複行」的去重/統計工具

核心限制:只能處理相鄰的重複行。非連續重複需先 sort 再 uniq (即經典 sort | uniq 模式)。

測試數據準備

$ cat test
boy took bat home
boy took bat home
girl took bat home
dog brought hat home
dog brought hat home
dog brought hat home

參數全景表與輸出演示

命令參數含義輸出說明
uniq test無參數:顯示去重後行 (連續重複只保留第一行)boy took bat home
girl took bat home
dog brought hat home
基礎去重
uniq -c test-c (count):行首顯示連續出現次數2 boy took bat home
1 girl took bat home
3 dog brought hat home
統計頻次,配合 sort -nr 找高頻行
uniq -d test-d (duplicate):僅顯示有連續重複的行 (每組一行)boy took bat home
dog brought hat home
找重複行,不顯示計數
uniq -u test-u (unique):僅顯示無連續重複的行 (唯一行)girl took bat home找獨特行
uniq -f 2 -s 2 test-f N:忽略前 N 個字段 (空白分隔)
-s N:忽略第 N+1 字段的前 N 個字符
boy took bat home精準控制比較範圍
uniq -f 1 test忽略第 1 字段 (boy/girl/dog)boy took bat home
dog brought hat home
視「took bat home」為連續重複

參數深度解析

-f N (--skip-fields=N) 忽略前 N 字段

  • 字段定義:由空白字符 (空格/Tab) 分隔的非空字符串。
  • uniq -f 1 比較時跳過第一個單詞,上例中 boy took bat home 和 girl took bat home 視為相同 (均為 took bat home)。

-s N (--skip-chars=N) 忽略字符

  • 在跳過字段後,進一步跳過下一字段的前 N 個字符。
  • 上例 -f 2 -s 2:忽略前 2 字段 (boy took/girl took/dog brought),再忽略第 3 字段 (bat/bat/hat) 前 2 字符 → 比較內容為 t home/t home/t home (全部相同) → 僅輸出第一行。

-w N (--check-chars=N) 限制比較字符數

  • 僅比較每行前 N 個字符 (含空白),超出部分忽略。
  • uniq -w 6 僅比較前 6 字符。

實戰組合拳

1. 統計日誌中高頻 IP (經典 sort | uniq -c | sort -nr)

awk '{print $1}' access.log | sort | uniq -c | sort -nr | head -20

2. 檢測配置文件重複行 (含註釋/空行)

grep -v '^#' nginx.conf | grep -v '^$' | sort | uniq -d
# 找出非註釋非空行的重複配置項

3. 監控系統調用頻率

strace -c -p  2>&1 | tail -20 | uniq -c
# 統計系統調用分布 (需配合其他工具)

4. 結合 cut/awk 提取字段去重

# 只比較第 2、3 字段
awk '{print $2, $3}' data.txt | sort | uniq -c

避坑指南

  • 未排序直接 uniq:非連續重複不會被合併 — **必須 sort 先**。
  • 大文件內存壓力:sort 需載入內存,超大文件用 sort -T /tmp --buffer-size=1G 或分片處理。
  • 區分大小寫:默認區分,sort -f / uniq -i 忽略大小寫。
  • 與 sort -u 區別:sort -u = sort | uniq (全局去重);uniq 僅連續去重 — **語義不同,不可混用**。

結語

uniq 是「連續去重」專家,sort 是「全局排序」基石。組合 sort | uniq -c | sort -nr 是文本頻率分析的黃金管道。掌握 -f/-s/-w 字段/字符級控制,能處理結構化日誌、配置審計等進階場景。下次面對幾百 MB 日誌找高頻異常,這條管道是你的核心武器。

Copyright © Windows教程網 All Rights Reserved