0

In Linux, how can I merge two files and only keep lines that have a match in both files?

Each line is separated by a newline (\n).

So far, I found to sort it, then use comm -12. Is this the best approach (assuming it's correct)?

fileA contains

aaa
bbb
ccc
ddd

fileB contains

aaa
ddd
eee

and I'd like a new file to contain

aaa
ddd
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
d-_-b
  • 21,536
  • 40
  • 150
  • 256

1 Answers1

2

Provided both of your two input files are lexicographically sorted, you can indeed use comm:

$ comm -12 fileA fileB > fileC

If that's not the case, you should sort your input files first:

$ comm -12 <(sort fileA) <(sort fileB) > fileC
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
elmov
  • 286
  • 1
  • 11