Skip to content

uniq 命令

基本用法

去重

bash
#!/bin/bash

# 去重
uniq file.txt

统计重复

bash
#!/bin/bash

# 统计重复
uniq -c file.txt

常用选项

-c 选项

bash
#!/bin/bash

# 统计重复次数
uniq -c file.txt

-d 选项

bash
#!/bin/bash

# 只显示重复行
uniq -d file.txt

-u 选项

bash
#!/bin/bash

# 只显示不重复行
uniq -u file.txt

-f 选项

bash
#!/bin/bash

# 跳过前 2 个字段
uniq -f2 file.txt

-s 选项

bash
#!/bin/bash

# 跳过前 2 个字符
uniq -s2 file.txt

实用示例

示例1:去重

bash
#!/bin/bash

# 去重
uniq file.txt

# 先排序再去重
sort file.txt | uniq

示例2:统计重复

bash
#!/bin/bash

# 统计重复
uniq -c file.txt

# 先排序再统计
sort file.txt | uniq -c

示例3:过滤重复

bash
#!/bin/bash

# 只显示重复行
uniq -d file.txt

# 只显示不重复行
uniq -u file.txt

示例4:跳过字段

bash
#!/bin/bash

# 跳过前 2 个字段
uniq -f2 file.txt

# 跳过前 2 个字符
uniq -s2 file.txt

最佳实践

1. 先排序

bash
# 好的做法
sort file.txt | uniq

# 不好的做法
uniq file.txt

2. 使用 -c 选项

bash
# 好的做法
sort file.txt | uniq -c

# 不好的做法
sort file.txt | uniq | wc -l

3. 使用 -d 选项

bash
# 好的做法
sort file.txt | uniq -d

# 不好的做法
sort file.txt | uniq | sort | uniq -d

总结

uniq 命令的关键点:

  1. 基本用法uniq file.txt
  2. 常用选项-c-d-u-f-s
  3. 实用示例:去重、统计重复、过滤重复、跳过字段
  4. 最佳实践:先排序、使用 -c 选项、使用 -d 选项

下一节我们将学习文件信息的使用。