user775187
user775187

Reputation: 23441

grep count search multiple words

how do I search for lines that contain multiple words? I want an "AND" relationship. I want a total count of such lines.

grep -c -E "tok1.*tok2" file

return 0

Upvotes: 2

Views: 7050

Answers (3)

glenn jackman
glenn jackman

Reputation: 246807

In addition to grep, there is awk:

awk '/tok1/ && /tok2/ {count++} END {print count}' file

Upvotes: 3

dolphy
dolphy

Reputation: 6498

To use grep specifically, you can use the OR operator to allow for both possibilities:

grep -c -E "(.*tok1.*tok2.*|.*tok2.*tok1.*)" file

You can also simply grep for one token, and then pipe that to a recurring grep for another token:

grep "tok1" file | grep -c "tok2"

Multiple greps seem to be much faster when you start introducing a lot of tokens. You can also substitute for the egrep command, which is a regexp version of grep...but I avoid it for the same reason: it seems to me to take drastically longer when you introduce multiple terms into the search.

Upvotes: 4

frankc
frankc

Reputation: 11473

egrep "tok1" file | egrep -c "tok2"

Upvotes: 1

Related Questions