【问题标题】:Matching emails from second column in one file against another file将一个文件中第二列的电子邮件与另一个文件匹配
【发布时间】:2019-12-29 09:33:09
【问题描述】:

我有两个文件,一个包含电子邮件(useremail.txt),另一个包含电子邮件:电话号码(emailnumber.txt)。

useremail.txt 包含:

John smith:blabla@hotmail.com

David smith:haha@gmail.com

emailnumber.txt 包含:

blabla@hotmail.com:093748594

所以解决方案需要从 useremail 的第二列中抓取电子邮件,然后搜索 emailnumber 文件并找到匹配项并输出 John smith:093748594,所以只有姓名和电话号码。

我在 Windows 上,所以我需要一个 gawk 或 grep 解决方案,我已经尝试了很长时间试图让它与 awk/grep 一起工作,但找不到合适的解决方案,任何帮助将不胜感激。

【问题讨论】:

    标签: linux awk grep


    【解决方案1】:

    (GNU) awk 中的另一个:

    $ awk '
    BEGIN {
        # RS=ORS="\r\n"       # since you are using GNU awk this replaces the sub()
        FS=OFS=":"            # input and output field separators
    }
    NR==FNR {                 # processing the first file
        sub(/\r$/,"",$NF)     # remove the \r after the email OR uncomment RS above
        a[$2]=$1              # hash name, index on email
        next                  # on to the next record
    }
    ($1 in a) {               # if email in second file matches one in hash
        print a[$1],$2        # output. If ORS uncommented above, output ends in \r
                              # if not, you may want to add it to the print ... "\r"
    }' useremail emailnumber
    

    输出:

    John smith:093748594
    

    由于您在 Linux 和 Windows 中尝试了接受的答案并且您使用 GNU awk,因此将来您可以设置RS="\r?\n",它接受\r\n 和裸\n 这两种形式。但是,我最近在特定条件下遇到了该表单的问题(我尚未提交错误报告)。

    【讨论】:

      【解决方案2】:

      你可以试试这个:

       awk -F":" '(FNR==NR){a[$2]=$1}(FNR!=NR){print a[$1]":"$2}' useremail.txt emailnumber.txt
      

      如果emailnumber.txt 中有条目而useremail.txt 中没有匹配条目:

      awk -F":" '(FNR==NR){a[$2]=$1}(FNR!=NR){if(a[$1]){print a[$1]":"$2}}' useremail.txt emailnumber.txt
      

      【讨论】:

      • 似乎对我不起作用,它只是打印出一堆电子邮件,前面带有 : ,来自 emailnumber 文件的电子邮件甚至不在 useremail 文件中。您的命令与 gawk 兼容吗?我试过 cygwin 和同样的东西。
      • 您能否提供一个更大的示例数据集?对我来说,它适用于给定的数据。你能再检查一下吗?我把 2 美元和 1 美元混在一起。
      • 是的,我发现了 $2/$1 的东西,但是在使用你的第二个版本之后它是有意义的,它似乎不匹配,无论出于何种原因。我在我的 linux 虚拟机上试过,它工作正常,我想我只需要移动文件,非常感谢。
      • 这是因为你有 Windows 行尾,即。 \r\n 和电子邮件将被处理为blabla@hotmail.com\r。在处理useremail.txt 时使用sub(/\r$/,"",$NF) 删除\r,或任何适合您方案的类似内容。
      猜你喜欢
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 2015-08-07
      • 1970-01-01
      相关资源
      最近更新 更多