歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> Linux刪除重復行的代碼

Linux刪除重復行的代碼

日期:2017/3/1 18:12:19   编辑:Linux技術

文本處理時,經常要刪除重復行,下面是三種方法

第一,用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

Copyright © Linux教程網 All Rights Reserved