uniq
uniq 是 Unix/Linux 环境中常用的文本处理工具,专门用于报告或省略相邻的重复行,常与 sort、cat、grep 等工具结合使用。
uniq [选项] [输入文件] [输出文件]uniq 只能识别相邻的重复行,因此通常需要先用 sort 排序后再使用
| 选项 | 含义 |
|---|---|
-c |
显示每行重复的次数 |
-d |
只显示重复出现的行 |
-u |
只显示唯一出现的行 |
-i |
忽略大小写比较 |
-f N |
从每一行的第 N+1 个字段开始比较(以空格分隔字段) |
-s N |
从每行第 N+1 个字符开始比较 |
-w N |
只比较每行的前 N 个字符 |
示例数据:
-- fruits.txt --appleapplebananacherrycherrycherrybanana1. 去除相邻重复行
sort fruits.txt | uniq输出:
applebananacherry2. 统计每行出现的次数(-c)
sort fruits.txt | uniq -c输出:
2 apple 2 banana 3 cherry3. 只显示重复出现的行(-d)
sort fruits.txt | uniq -d输出:
applebananacherry4. 只显示唯一出现的行(-u)
sort fruits.txt | uniq -u上例中所有行都重复出现,因此无输出
5. 忽略大小写比较(-i)
printf "Hello\nhello\nHELLO\n" | uniq -i输出:
Hello6. 跳过前 N 个字段比较(-f)
printf "2025 apple\n2024 apple\n2025 banana\n" | uniq -f 1输出:
2025 apple2025 banana跳过第 1 个字段(年份),只比较后面的内容
man uniq- GNU Coreutils - uniq