grep egrep multiple-strings

2020-02-28 00:00发布

Suppose I have several strings: str1 and str2 and str3.

  • How to find lines that have all the strings?
  • How to find lines that can have any of them?
  • And how to find lines that have str1 and either of str2 and str3 [but not both?]?

标签: regex grep
4条回答
一纸荒年 Trace。
2楼-- · 2020-02-28 00:12

This looks like three questions. The easiest way to put these sorts of expressions together is with multiple pipes. There's no shame in that, particularly because a regular expression (using egrep) would be ungainly since you seem to imply you want order independence.

So, in order,

  1. grep str1 | grep str2 | grep str3

  2. egrep '(str1|str2|str3)'

  3. grep str1 | egrep '(str2|str3)'

you can do the "and" form in an order independent way using egrep, but I think you'll find it easier to remember to do order independent ands using piped greps and order independent or's using regular expressions.

查看更多
三岁会撩人
3楼-- · 2020-02-28 00:20

You can't reasonably do the "all" or "this plus either of those" cases because grep doesn't support lookahead. Use Perl. For the "any" case, it's egrep '(str1|str2|str3)' file.

The unreasonable way to do the "all" case is:

egrep '(str1.*str2.*str3|str3.*str1.*str2|str2.*str1.*str3|str1.*str3.*str2)' file

i.e. you build out the permutations. This is, of course, a ridiculous thing to do.

For the "this plus either of those", similarly:

egrep '(str1.*(str2|str3)|(str2|str3).*str1)' file
查看更多
相关推荐>>
4楼-- · 2020-02-28 00:24

grep -E --color "string1|string2|string3...."

for example to find whether our system using AMD(svm) or Intel(vmx) processor and if it is 64bit(lm) lm stands for long mode- that means 64bit...

command example:

grep -E --color "lm|svm|vmx" /proc/cpuinfo

-E is must to find multiple strings

查看更多
一夜七次
5楼-- · 2020-02-28 00:36

Personally, I do this in perl rather than trying to cobble together something with grep.

For instance, for the first one:

while (<FILE>)
{
   next if ! m/pattern1/;
   next if ! m/pattern2/;
   next if ! m/pattern3/;

   print $_;
}
查看更多
登录 后发表回答