比较两个文本文件中的列并匹配行

编程入门 行业动态 更新时间:2024-10-28 19:35:56
本文介绍了比较两个文本文件中的列并匹配行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想比较file1中的第二列(由空格分隔):

I want to compare the second column (delimited by a whitespace) in file1:

n01443537/n01443537_481.JPEG n01443537 n01629819/n01629819_420.JPEG n01629819 n02883205/n02883205_461.JPEG n02883205

在file2中使用第二列(由空格分隔):

With the second column (delimited by a whitespace) in file2:

val_8447.JPEG n09256479 val_68.JPEG n01443537 val_1054.JPEG n01629819 val_1542.JPEG n02883205 val_8480.JPEG n03089624

如果有匹配项,我想打印出file2的相应行.

If there is a match, I would like to print out the corresponding line of file2.

在此示例中所需的输出:

Desired output in this example:

val_68.JPEG n01443537 val_1054.JPEG n01629819 val_1542.JPEG n02883205

我尝试了以下操作,但是输出文件为空:

I tried the following, but the output file is empty:

awk -F' ' 'NR==FNR{c[$2]++;next};c[$2] > 0' file1.txt file2.txt > file3.txt

也尝试过此方法,但结果是相同的(空输出文件):

Also tried this, but the result was the same (empty output file):

awk 'NR==FNR{a[$2];next}$2 in a' file1 file2 > file3.txt

推荐答案

使用awk:

awk 'FNR==NR{a[$NF]; next} $NF in a' file1 file2 val_68.JPEG n01443537 val_1054.JPEG n01629819 val_1542.JPEG n02883205

这是带有进程替换的grep替代项:

Here is a grep alternative with process substitution:

grep -f <(awk '{print " " $NF "$"}' file1) file2

使用print " " $NF "$"创建类似于" n01443537$"的正则表达式,以便我们仅匹配grep中的最后一列.

Using print " " $NF "$" to create a regex like " n01443537$" so that we match only last column in grep.

更多推荐

比较两个文本文件中的列并匹配行

本文发布于:2023-05-29 16:43:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/348716.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!