当前位置: 移动技术网 > 科技>操作系统>Linux > Linux删除重复行的代码

Linux删除重复行的代码

2019年03月25日  | 移动技术网科技  | 我要评论

文本处理时,经常要删除重复行,下面是三种方法

第一,用sort+uniq,注意,单纯uniq是不行的。

sort -n test.txt | uniq 

第二,用sort+awk命令,注意,单纯awk同样不行,原因同上。

 sort -n $file | awk '{if($0!=line)print; line=$0}'
 
第三,用sort+sed命令,同样需要sort命令先排序。
sort -n $file | sed '$!n; /^.∗\n\1$/!p; d'

shell脚本

# !/bin/sh

file='test.txt'
sort -n $file | uniq
sort -n $file | awk '{if($0!=line)print; line=$0}'
sort -n $file | sed '$!n; /^\(.*\)\n\1$/!p; d'

测试文件:
yanggang@barry$ cat test.txt
aaa
bbbbb
ccccc
123
aaaaa
123
bbb
aaa
执行结果:
yanggang@barry$ ./diffrow.sh
aaa
aaaaa
bbb
bbbbb
ccccc
123

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网