d-_-b
d-_-b

Reputation: 23211

Merge two files on Linux keeping only lines that appear in both files

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

Upvotes: 0

Views: 820

Answers (1)

elmov
elmov

Reputation: 286

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

Upvotes: 2

Related Questions