如何使用awk测试列值是否在另一个文件中? [英] How to use awk to test if a column value is in another file?

查看:398
本文介绍了如何使用awk测试列值是否在另一个文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做

if ($2 in another file) { print $0 }

所以说我有一个包含

aa
bb
cc

我有B.txt之类的

00,aa
11,bb
00,dd

我要打印

00,aa
11,bb

如何在awk中进行测试?我不熟悉一次处理两个文件的技巧.

How do I test that in awk? I am not familiar with the tricks of processing two files at a time.

推荐答案

您可以使用以下内容:

awk -F, 'NR == FNR { a[$0]; next } $2 in a' A.txt B.txt

这会将A.txt中的每一行保存为数组a中的键,然后打印B.txt中第二个字段位于数组中的任何行.

This saves each line from A.txt as a key in the array a and then prints any lines from B.txt whose second field is in the array.

NR == FNR是将传递给awk的第一个文件作为目标的标准方法,因为对于第一个文件,NR(总记录号)仅等于FNR(当前文件的记录号). next跳至下一个记录,因此直到第二个文件之前,都不会到达$2 in a部分.

NR == FNR is the standard way to target the first file passed to awk, as NR (the total record number) is only equal to FNR (the record number for the current file) for the first file. next skips to the next record so the $2 in a part is never reached until the second file.

这篇关于如何使用awk测试列值是否在另一个文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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