0

For instance, I have two files. File1 contains:

12
13
14
15

File2 contains:

13,abc,xyz
14,def,ghi
15,klm,opq

expected output in file3:

13,abc,xyz
14,def,ghi
15,klm,opq

I am on a Linux machine. What would the command be?

1 Answer 1

3

Strictly speaking, we're not interested in common lines (there are no common lines in the given data), but in the intersection of the data based on the first column.

Using join:

$ join -t, File1 File2
13,abc,xyz
14,def,ghi
15,klm,opq

The join utility does an efficient relational (inner) JOIN operation between two files given some own field in each (by default the first field). I use it with -t , to tell it that commas are field delimiters in the files (it uses any whitespace otherwise). The command will by default create the intersection based on the first field of both files.

Note that both files need to be sorted on the join field (the first column), which they appear to be in the question. If they are not sorted, you may sort them on the fly with

join -t, <( sort File1 ) <( sort File2 )

if your shell supports process substitutions.

2
  • 1
    Could decorate with join -t, <(sort File1) <(sort File2)...
    – vonbrand
    Mar 5, 2020 at 21:10
  • @vonbrand Thanks, added a short note about that.
    – Kusalananda
    Mar 5, 2020 at 21:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .