sanjihan
sanjihan

Reputation: 6026

find the intersection of 4 files

How do you find intersection of 4 files?

I used grep -Fx -f 1.txt 2.txt 3.txt 4.txt, but it seems that it only works for 2 files. Similarly comm -12 1.txt 2.txt can't be expanded to 4 files and requires data to be sorted. My data isn't sorted, in fact, it shouldn't be. I am on Mac.

Input:

1.txt
.css
.haha
.hehe
2.txt
.ajkad
.shdja
.hehe

3.txt
.css1
.aaaaa
.hehe

4.txt
.qwqw
.kkkmsm
.hehe

Output: .hehe

I used grep first on 1 and 2 stored in 12.txt, than on 3 and 4,stored in 34.txt then used grep again on 12.txt and 34.txt. But there must be a better way of doing this.

Upvotes: 0

Views: 74

Answers (2)

dawg
dawg

Reputation: 104092

You can find the intersection between two:

$ grep -Fx -f f1.txt f2.txt
.hehe

Then use that as input with the other two:

$ grep -f <(grep -Fx -f f1.txt f2.txt) f3.txt f4.txt
f3.txt:.hehe
f4.txt:.hehe

Or, if you just want a single word:

$ grep -f <( grep -f <(grep -Fx -f f1.txt f2.txt) f3.txt) f4.txt
.hehe

Upvotes: 1

choroba
choroba

Reputation: 242168

You can chain the greps:

grep -f 1.txt 2.txt \
| grep -f- 3.txt \
| grep -f- 4.txt

The -f- means the input coming from the pipe is used, not a real file.

Upvotes: 1

Related Questions