linux命令(50):comm命令的用法,求交集

Linux comm命令

使用局限比较大,适用于特殊场合;

Linux comm命令用于比较两个已排过序的文件。

排序:sort -u file

这项指令会一列列地比较两个已排序文件的差异,并将其结果显示出来;

如果没有指定任何参数,则会把结果分成3行显示:

  • 第1行仅是在第1个文件中出现过的列
  • 第2行是仅在第2个文件中出现过的列
  • 第3行则是在第1与第2个文件里都出现过的列

若给予的文件名称为"-",则comm指令会从标准输入设备读取数据。

语法

comm [-123][--help][--version][第1个文件][第2个文件]

参数

  • -1 不显示只在第1个文件里出现过的列。
  • -2 不显示只在第2个文件里出现过的列。
  • -3 不显示只在第1和第2个文件里出现过的列。
  • --help 在线帮助。
  • --version 显示版本信息。

实例

aaa.txt 与 bbb.txt 的文件内容如下:

[root@localhost text]# cat aaa.txt 
aaa 
bbb 
ccc 
ddd 
eee 
111 
222
[root@localhost text]# cat bbb.txt
bbb 
ccc 
aaa 
hhh 
ttt 
jjj
执行 comm 命令输出结果如下:
[root@localhost text]# comm aaa.txt bbb.txt 
aaa
                bbb
                ccc
        aaa
ddd
eee
111
222
        hhh
        ttt
        jjj
第一列  第二列  第三列

输出的第一列只包含在aaa.txt中出现的行,第二列包含在bbb.txt中出现的行,第三列包含在aaa.txt和bbb.txt中相同的行。

具体实例讲解

1、以下(A==file_1 and  B==file_2)

2、选项:-12 == -21  -23==-32  -31==-13

组合使用一:输出只有一列

1、w@ubuntu:~/work/linshi$ cat aa_sort.txt
111
222
aaa
bbb
ccc
ddd
eee
2、w@ubuntu:~/work/linshi$ cat bb_sort.txt
aaa
bbb
ccc
hhh
jjj
ttt 

3、comm -12 A B

表达意义:(AnB)

w@ubuntu:~/work/linshi$ comm -12 aa_sort.txt bb_sort.txt
aaa
bbb
ccc

4、comm -13 A B

表达意义:B-(AnB)

w@ubuntu:~/work/linshi$ comm -13 aa_sort.txt bb_sort.txt
hhh
jjj
ttt

5、comm -23 A B

表达意义:A-(AnB)

w@ubuntu:~/work/linshi$ comm -23 aa_sort.txt bb_sort.txt
111
222
ddd
eee

实质上:(comm -1) or (comm -2) or (comm -3),每个命令都会输出两列,两列的内容 等于如下表示:

各列是以制表符( )作为定界符。

6、comm -1 == comm -13 -12

w@ubuntu:~/work/linshi$ comm -1 aa_sort.txt bb_sort.txt
  aaa
  bbb
  ccc
hhh
jjj
ttt

7、comm -2 == comm -23 -21

w@ubuntu:~/work/linshi$ comm -2 aa_sort.txt bb_sort.txt
111
222
  aaa
  bbb
  ccc
ddd
eee

8、comm -3 == comm -32 -31

w@ubuntu:~/work/linshi$ comm -3 aa_sort.txt bb_sort.txt
111
222
ddd
eee
  hhh
  jjj
  ttt

9、默认情况下:comm A B== -23 -13 -12

w@ubuntu:~/work/linshi$ comm aa_sort.txt bb_sort.txt
111
222
    aaa
    bbb
    ccc
ddd
eee
  hhh
  jjj
  ttt

原文地址:https://www.cnblogs.com/lovychen/p/8917352.html