Linux uniq 命令
Linux uniq 命令
Linux uniq 命令用于检查及删除文本文件中重复出现的行列,一般与 sort 命令结合使用。
uniq 可检查文本文件中重复出现的行列。
语法
uniq [-cdu][-f<栏位>][-s<字符位置>][-w<字符位置>][--help][--version][输入文件][输出文件]
参数:
1 -c或--count 在每列旁边显示该行重复出现的次数。 2 -d或--repeated 仅显示重复出现的行列。 3 -f<栏位>或--skip-fields=<栏位> 忽略比较指定的栏位。 4 -s<字符位置>或--skip-chars=<字符位置> 忽略比较指定的字符。 5 -u或--unique 仅显示出一次的行列。 6 -w<字符位置>或--check-chars=<字符位置> 指定要比较的字符。 7 --help 显示帮助。 8 --version 显示版本信息。 9 [输入文件] 指定已排序好的文本文件。如果不指定此项,则从标准读取数据; 10 [输出文件] 指定输出的文件。如果不指定此选项,则将内容显示到标准输出设备(显示终端)。
例子:
1 # uniq.txt 2 My name is Delav 3 My name is Delav 4 My name is Delav 5 I'm learning Java 6 I'm learning Java 7 I'm learning Java 8 who am i 9 Who am i 10 Python is so simple 11 My name is Delav 12 That's good 13 That's good 14 And studying Golang
1. 直接去重
uniq uniq.txt
1 3 My name is Delav 2 3 I'm learning Java 3 1 who am i 4 1 Who am i 5 1 Python is so simple 6 1 My name is Delav 7 2 That's good 8 1 And studying Golang
你会发现,上面有两行 ”My name is Delav ” 是相同的。也就是说,当重复的行不相邻时,uniq 命令是不起作用的。所以,经常需要跟 sort 命令一起使用。
1 sort uniq.txt | uniq -c
1 1 And studying Golang 2 3 I'm learning Java 3 4 My name is Delav 4 1 Python is so simple 5 2 That's good 6 1 who am i 7 1 Who am i
3. 只显示重复的行,并显示重复次数
1 uniq -cd uniq.txt
1 3 My name is Delav 2 3 I'm learning Java 3 2 That's good
显示所有重复的行,不能与 -c 一起使用
1 uniq -D uniq.txt
结果为:
1 My name is Delav 2 My name is Delav 3 My name is Delav 4 I'm learning Java 5 I'm learning Java 6 I'm learning Java 7 That's good 8 That's good
4. 忽略第几列字符
下面这里 -f 1 忽略了第一列字符,所以"who am i" 和 "Who am i" 判定为重复
uniq -c -f 1 uniq.txt
1 3 My name is Delav 2 3 I'm learning Java 3 2 who am i 4 1 Python is so simple 5 1 My name is Delav 6 2 That's good 7 1 And studying Golang
5. 忽略大小写
下面这里 -i 忽略了大小写,所以"who am i" 和 "Who am i" 判定为重复
uniq -c -i uniq.txt
1 3 My name is Delav 2 3 I'm learning Java 3 2 who am i 4 1 Python is so simple 5 1 My name is Delav 6 2 That's good 7 1 And studying Golang
6. 忽略前面N个字符
下面这里 -s 4 表示忽略前面四个字符,所以"who am i" 和 "Who am i" 判定为重复
uniq -c -s 4 uniq.txt
1 3 My name is Delav 2 3 I'm learning Java 3 2 who am i 4 1 Python is so simple 5 1 My name is Delav 6 2 That's good 7 1 And studying Golang
7. 忽略第N个字符后的内容
1 uniq -c -w 2 uniq.txt