bash grep 计数搜索多个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6297491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
grep count search multiple words
提问by user775187
how do I search for lines that contain multiple words? I want an "AND" relationship. I want a total count of such lines.
如何搜索包含多个单词的行?我想要一个“AND”关系。我想要这些行的总数。
grep -c -E "tok1.*tok2" file
return 0
返回 0
回答by dolphy
To use grep specifically, you can use the OR operator to allow for both possibilities:
要专门使用 grep,您可以使用 OR 运算符来实现两种可能性:
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 一个令牌,然后将其通过管道传递给另一个令牌的重复 grep:
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 egrepcommand, 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.
当您开始引入大量令牌时,多个 grep 似乎要快得多。您还可以替换egrep命令,它是 grep 的正则表达式版本……但我出于同样的原因避免使用它:在我看来,当您在搜索中引入多个术语时,需要花费更长的时间。
回答by glenn Hymanman
In addition to grep, there is awk:
除了grep,还有awk:
awk '/tok1/ && /tok2/ {count++} END {print count}' file
回答by frankc
egrep "tok1" file | egrep -c "tok2"
egrep "tok1" 文件 | egrep -c "tok2"

