[精彩] comm, an easy and powerful command |
|
| 来源 chinaunix.net 酷勤网整理 |
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. :-)
ZealeS 回复于:2005-12-16 09:51:48
我的记忆是判断那个文件没有的,就把参数去掉。都有的才
file1中有file2中没有 comm -23 #(file1有,把1去掉)
file1没有有file2中有 comm -13 #(file2有,把2去掉)
file1和file2都存在 comm -12 #(都有,把3去掉)
寂寞烈火 回复于:2005-12-16 12:09:41
使用comm需要注意的是下面的红字
compare two [color=red]sorted files[/color] line by line
icesummit 回复于:2005-12-16 13:19:06
引用:原帖由 寂寞烈火 于 2005-12-16 12:09 发表
使用comm需要注意的是下面的红字
compare two [color=red]sorted files[/color] line by line
Right!
大蚂蚁 回复于:2005-12-16 13:43:57
我习惯用win下的UltraEdit 没排序的一样比较 :mrgreen:
dbcat 回复于:2005-12-16 13:47:28
嘻,学习!
|
 |
原文链接:http://bbs.chinaunix.net/viewthread.php?tid=669957
转载请注明作者名及原文出处
|
|
|