在另一个文件中查找文件的模式并打印出后者的相应字段保持顺序 [英] Find patterns of a file in another file and print out a corresponding field of the latter maintaining the order
问题描述
我已经尝试了一段时间来解决这个问题,我检查了很多帖子(例如这里 在一个文件中打印匹配另一个文件中的模式的行 或在这里 awk 搜索另一个文件中的字段),而没有真正找到我要找的东西.我需要使用 sed、grep、awk 等 bash 工具的解决方案(没有 python、R...)
I've been trying for a while to solve this problem and I checked many posts (for example here Print lines in one file matching patterns in another file or here awk search for a field in another file) without really finding what I am looking for. I need the solution with bash tools like sed, grep, awk (no python, R,...)
我有两个文件(比那些文件大得多):
I have two files (much bigger than those):
文件 1:
2 891299 0.50923964E-02 1248 4.713 1349.08
3 245857 0.57915542E-02 1335 4.671 1369.65
文件 2:
278 2645 2334659 0.75142 0.53123
279 2643 245857 0.80439 0.56868
500 1341 830677 0.74922 0.52958
501 1339 882791 0.87685 0.61980
502 1337 891299 0.63224 0.44680
在这个例子中,我想在 file2 的第 3 列中找到 file1 的第 2 列中的模式,并打印后者的第 1 列,对于 file1 的所有行并保持 file1 给出的顺序.
In this example I want to find the pattern in column 2 of file1 in column 3 of file2 and print column 1 of the latter, for all the lines of file1 and maintaining the order given by file1.
一个可能的解决方案(我知道不是没有错误)是以下慢得无法接受的 bash 循环:
A possible solution (I am aware is not bug free) is the following unacceptably slow bash loop:
for i in `awk '{print $2}' file1` ; do grep " $i " file2 | awk '{print $1}' ; done
打印到屏幕:
502
279
请注意一个简单"的解决方案,例如:
Please note that a 'simple' solution like:
awk 'NR==FNR{pats[$2]; next} $3 in pats' file1 file2
不合适,因为打印顺序是由 file2 而不是由 file1 给出的(即它先打印到屏幕 279 然后是 502).
is not appropriate as the order of the printing is given by file2 and not by file1 (i.e. it prints to screen first 279 and then 502).
非常感谢您的帮助.
推荐答案
您可以在 awk 中反转要处理的文件并获得正确的输出:
You can reverse files to be processed in awk and get the right output:
awk 'NR==FNR{pats[$3]=$1; next} $2 in pats{print pats[$2]}' file2 file1
502
279
这篇关于在另一个文件中查找文件的模式并打印出后者的相应字段保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!