Daniel YC Lin
Daniel YC Lin

Reputation: 15992

How to find files contains both keywords on different line by grep?

There are many files in Linux kernel source config/* I want to found one which is similar to my board.

So I try:

egrep -l -e key1 -e key2 config/*

Sample config/file1:
    This is key1
    This is key2
Sample config/file2:
    This is key1
Sample config/file3:
    This is key2

But the result is either key1 or key2 file listing. I want the result which contains key1 and key2 or is there other easy unix shell which can generate the result?

In the previsous sample I just want to list 'file1'.

Upvotes: 3

Views: 373

Answers (2)

ashdaha
ashdaha

Reputation: 21

My suggestion:

( grep -l key1 config/* ; grep -l key2 config/* ) |sort |uniq -c |grep '^ *2\>' |awk '{print $2}'

First grep prints all files that contain key1, second grep prints all files that contain key2, and then sort, uniq and third grep filter for files listed twice, i.e. containing both keys.

Upvotes: 2

user1666959
user1666959

Reputation: 1855

'grep -E 'pat1.*pat2|pat2.*pat1'' is my usual incantation. axiom's solution only works if those patterns appear in the order given, the '|' regular expression operator allows the search to find the patterns in any order.

Upvotes: 0

Related Questions