首页 > 解决方案 > 仅使用 grep 返回匹配模式 aginst 文件

问题描述

我正在尝试使用 grep 将电子邮件列表与另一个列表反向分离,以便仅返回与这些表达式不匹配的电子邮件。

电子邮件列表如下所示:

   recruitment@madeup.com
   joy@netnoir.net
   hello@nom.com
   mary@itcouldbereal.ac.uk
   thisshouldbe@theonlyone.com

我与之比较的表达式列表是:

   recruitment@
   netnoir.net
   hello@
   "\.ac.\b"

我试过了:

   grep -vif listofexpressions listofemails

我面临的问题是

1.) 不返回任何内容 2.) .ac。在文件中无法识别,但如果我使用它

            grep "\.ac.\b" filename 

然后它会。

如果我将其更改为

        grep -if listofexpressions listofemails

然后大多数不需要转义的表达式被突出显示,但其他表达式也被显示。

我的预期输出是

      thisshouldbe@theonlyone.com

我确信这很简单,但是在阅读了 grep 和谷歌搜索的手册页之后,我仍然无法解决。

谢谢

标签: awkgrep

解决方案


使用您显示的示例,您能否尝试以下操作。用 GNU 编写和测试awk

awk '
FNR==NR{
  arr[$0]
  next
}
{
  found=""
  for(key in arr){
    if(index($0,key)){
      found=1
      next
    }
  }
  if(found==""){
    print
  }
}
' expressions  listemail

说明:为上述添加详细说明。

awk '                        ##Starting awk program from here.
FNR==NR{                     ##Checking condition FNR==NR which will be TRUE when expressions file is being read.
  arr[$0]                    ##Created arr with index of current line here.
  next                       ##next will skip all further statements from here.
}
{
  found=""                   ##Nulliyfing found here.
  for(key in arr){           ##Going through arr elements here.
    if(index($0,key)){       ##Checking if current line is part of key by index.
      found=1                ##Setting found to 1 here.
      next                   ##next will skip all further statements.
    }
  }
  if(found==""){             ##Checking condition if found is NULL then print that line.
    print
  }
}
' expressions  listemails    ##Mentioning Input_files here.

推荐阅读