免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 986 | 回复: 3
打印 上一主题 下一主题

@如何删除重复的行?@ [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-27 19:44 |只看该作者 |倒序浏览

@如何删除重复的行?@









假如我们有一个文件file,然后想要删除该文件中重复的行,那么我们有哪些方法呢?

file文件的内容如下:

my friends, xiaoying
my teacher, xiaoniu
my teacher, xiaoniu
my fuqin, father
my sister, wushiying
my sister, wushiying
my friends, xiaoying
my teacher, xiaoniu
my fuqin, father
my sister, wushiying
my friends, xiaoying
my fuqin, father

方法一:awk '{if ($0!=line) print;line=$0}' file


也就是:

cat file |sort |awk '{if ($0!=line) print;line=$0}'【因为这个需要先排序,才能够用这样的方法~】


原理:

因为awk也是一次读入一行,line第一次为空【line 是 awk 的变量,像shell中的一样不需事先声明,没给它赋值前当然就是空的】

所以自然就不等于$0($0为"my friend,xiaoying"),所以就打印了;接着把line的值赋为$0;然后awk又读入一行,由于此时$0的值

与line相同(均为"my friend,xiaoying"),所以就不打印了。当读入"my teacher, liyong"时,$0与line(值为"my friend,xiaoying")又不

同了,所以打印出来,其余的以此类推。


方法二:【这个是最简单的~】

[root@sor-sys zy]# cat file| sort | uniq
my friends, xiaoying
my fuqin, father
my sister, wushiying
my teacher, xiaoniu


方法三:

文件rmdup.sed的内容如下:

#n rmdup.sed - ReMove DUPlicate consecutive lines

# read next line into pattern space (if not the last line)
$!N

# check if pattern space consists of two identical lines
s/^\(.*\)\n\1$/&/
# if yes, goto label RmLn, which will remove the first line in pattern space
t RmLn
# if not, print the first line (and remove it)
P

# garbage handling which simply deletes the first line in the pattern space
: RmLn
D


[root@sor-sys zy]# cat file|sort |sed -f rmdup.sed
my friends, xiaoying
my fuqin, father
my sister, wushiying
my teacher, xiaoniu

论坛徽章:
0
2 [报告]
发表于 2011-12-27 19:44 |只看该作者
谢谢分享

论坛徽章:
33
ChinaUnix元老
日期:2015-02-02 08:55:39CU十四周年纪念徽章
日期:2019-08-20 08:30:3720周年集字徽章-周	
日期:2020-10-28 14:13:3020周年集字徽章-20	
日期:2020-10-28 14:04:3019周年集字徽章-CU
日期:2019-09-08 23:26:2519周年集字徽章-19
日期:2019-08-27 13:31:262016科比退役纪念章
日期:2022-04-24 14:33:24
3 [报告]
发表于 2011-12-28 15:14 |只看该作者
本帖最后由 Shell_HAT 于 2011-12-28 15:14 编辑
cat file |sort |awk '{if ($0!=line) print;line=$0}'【因为这个需要先排序,才能够用这样的方法~】

awk初学者真是伤不起啊
  1. awk '!a[$0]++' urfile
复制代码

论坛徽章:
33
ChinaUnix元老
日期:2015-02-02 08:55:39CU十四周年纪念徽章
日期:2019-08-20 08:30:3720周年集字徽章-周	
日期:2020-10-28 14:13:3020周年集字徽章-20	
日期:2020-10-28 14:04:3019周年集字徽章-CU
日期:2019-09-08 23:26:2519周年集字徽章-19
日期:2019-08-27 13:31:262016科比退役纪念章
日期:2022-04-24 14:33:24
4 [报告]
发表于 2011-12-28 15:15 |只看该作者
方法二:【这个是最简单的~】

[root@sor-sys zy]# cat file| sort | uniq

其实吧,这样更简单:
  1. sort -u urfile
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP