danvoronov
danvoronov

Reputation: 83

Keep lines with multiple matches from file grep

I have two files:

the query.txt

i1  
i2
i3  
i4

and the subject.txt

2   i1  i2  p
3   i2  i5  p
1   i3  i4  p
2   i3  i4  p
1   i5  i1  p
1   i4  i2  p

I need to get the lines from subject.txt that have entries from query.txt in columns 2 and 3 of subject.txt (in any order), and I want to get rid of lines of subject.txt that has an entry from query.txt only in one of columns of subject.txt.

So I want to keep only:

2   i1  i2  p
1   i3  i4  p
1   i4  i2  p

Upvotes: 0

Views: 53

Answers (1)

glenn jackman
glenn jackman

Reputation: 246827

When you have logic that is column/field based, is a better tool to use:

awk '
    NR == FNR {q[$1] = 1; next}
    $2 in q && $3 in q
' query.txt subject.txt

Upvotes: 4

Related Questions