免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6021 | 回复: 6

comm, an easy and powerful command  关闭 [复制链接]

论坛徽章:
0
发表于 2005-12-15 23:24 |显示全部楼层
In our work, we often encounter the following questions:

I have two files: file1 and file2:
1) How can I print out the lines that are only contained in file1?
2) How can I print out the lines that are only contained in file2?
3) How can I print out the lines that are contained both in file1 and file2?

There is a powerful shell command that can easily meet our needs, it is: comm. When you meet the above questions, "comm" should be your first choice

comm [ -123 ]  file1  file2

comm will read file1 and file2 and generate three columns of output: lines only in file1; lines only  in file2; and lines in both files. For detailed explanation, pls man comm.

Example:

bash-2.03$ cat file1
11111111
22222222
33333333
44444444
55555555
66666666
77777777
88888888
99999999
bash-2.03$ cat file2
00000000
22222222
44444444
66666666
88888888

1)  Print out the lines that are only contained in file1?
bash-2.03$ comm -23 file1 file2
11111111
33333333
55555555
77777777
99999999

2)  Print out the lines that are only contained in file2?
bash-2.03$ comm -13 file1 file2
00000000

3)  Print out the lines that are contained both in file1 and file2
bash-2.03$ comm -12 file1 file2
22222222
44444444
66666666
88888888

Besides the comm, we still have various ways to finish the above tasks.

1)  Print out the lines that are only contained in file1?
diff file1 file2 | grep "^<"|sed 's/^< //g'

for i in $(<file1); do (grep $i file2)||echo $i>>temp ; done;
      cat temp


In comparison, comm is much easier to remember.

论坛徽章:
0
发表于 2005-12-16 09:51 |显示全部楼层
我的记忆是判断那个文件没有的,就把参数去掉。都有的才
file1中有file2中没有 comm -23             #(file1有,把1去掉)
file1没有有file2中有 comm -13             #(file2有,把2去掉)
file1和file2都存在   comm -12             #(都有,把3去掉)

论坛徽章:
1
荣誉会员
日期:2011-11-23 16:44:17
发表于 2005-12-16 12:09 |显示全部楼层
使用comm需要注意的是下面的红字
compare two sorted files line by line

论坛徽章:
0
发表于 2005-12-16 13:19 |显示全部楼层
原帖由 寂寞烈火 于 2005-12-16 12:09 发表
使用comm需要注意的是下面的红字
compare two sorted files line by line

Right!

论坛徽章:
0
发表于 2005-12-16 13:43 |显示全部楼层
我习惯用win下的UltraEdit  没排序的一样比较   

论坛徽章:
0
发表于 2005-12-16 13:47 |显示全部楼层
嘻,学习!

论坛徽章:
0
发表于 2007-11-04 21:44 |显示全部楼层
thanks a lot
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP