问题描述
我想比较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
.
这篇关于比较两个文本文件中的列并匹配行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!