4

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?

9

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
  • 5
    No need for awk: join -o 2.2 test test2 – Stéphane Chazelas Sep 21 '12 at 8:56
  • 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? – hhh Sep 25 '18 at 8:01
-1
awk 'NR==FNR{c[$1]++;next};c[$1] == 1' file1.txt file2.txt | awk ' { print $2 } '
  • Please improve your answer by adding an explanation of what your code does. – SabreWolfy Dec 2 '17 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.