比较两个文件以进行匹配,打印找到的所有匹配项 [英] compare two file for match, print all matching found

查看:79
本文介绍了比较两个文件以进行匹配,打印找到的所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将File1的column1的每个条目与File2进行比较,并同时打印两者. File1的Column1可能具有重复的条目.在重复输入的情况下,我只能看到一条输出行.但我都想要.

I am trying to compare each entry of column1 of of File1 against File2 and print both. Column1 of File1 might have duplicate entry. In case of duplicate entry I can see only one output line; but I want both.

我的代码是awk 'FNR==NR{a[$1]=$0;next}; $1 in a {print $0"\t"a[$1]}' File1.txt File2.txt

File1.txt

File1.txt

aa  c   d
aa  c   e

File2.txt

File2.txt

aa  5
aa  7
aa  9
bb  7
cc  1

预期产量

aa  5   aa  c   d
aa  7   aa  c   d
aa  9   aa  c   d
aa  5   aa  c   e
aa  7   aa  c   e
aa  9   aa  c   e

我的代码给了我

aa  5   aa  c   e
aa  7   aa  c   e
aa  9   aa  c   e

推荐答案

这是join命令的情况:

$ join File{1,2}.txt
aa c d 5
aa c d 7
aa c d 9
aa c e 5
aa c e 7
aa c e 9

输出不完全是您想要的,所以让我们对其进行修复:

The output's not quite what you want, so let's fix that:

$ join File{1,2}.txt | awk '{$1 = $1 FS $NF FS $1; $NF = ""; print}'
aa 5 aa c d
aa 7 aa c d
aa 9 aa c d
aa 5 aa c e
aa 7 aa c e
aa 9 aa c e


如果输入文件未排序,那么(假设您的shell是bash/ksh/zsh)


If the input files are not sorted, then (assuming your shell is bash/ksh/zsh)

join <(sort File1.txt) <(sort File2.txt)

请参见中的 3.5.6流程替换 bash手册.

See 3.5.6 Process Substitution in the bash manual.

这篇关于比较两个文件以进行匹配,打印找到的所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆