How to find out common elements between two files?

5,708

you could use the join command to join the files on a specific column, and awk to parse the output.

To join these files on column 1 pass the parameters -j 1 to the join command:

usr@srv % join -j 1 test test2 
12 1

13 2

14 2

15 6

Afterwards use awk to print only the second column:

usr@srv % join -j 1 test test2 | awk '{print $2}'
1

2

2

6
Share:
5,708

Related videos on Youtube

N. F.
Author by

N. F.

1/0

Updated on September 18, 2022

Comments

  • N. F.
    N. F. over 1 year

    For an example, I have 2 files having following info:

    File #1:

    12
    13
    14
    15
    

    File #2:

    12 1
    13 2
    14 2
    15 6
    16 7
    17 8
    

    Output File:

    1
    2
    2
    6
    

    In the output file, I want only the second column values of file #2 which has matched with the first column of file #1. Is there any utility function for that in Linux? I'm new in shell scripting, can anyone help me out?

  • Stéphane Chazelas
    Stéphane Chazelas over 11 years
    No need for awk: join -o 2.2 test test2
  • German
    German over 6 years
    Please improve your answer by adding an explanation of what your code does.
  • Madhan
    Madhan over 5 years
    Is there a way to specify standard output as stdin? I.e. the purpose is check common elements between all three files? Not just two? join f1 f2 > fr; join fr f3 -- something like join f1 f2 f3?