查找两个文件并打印匹配的内容

时间:2018-06-01 06:29:24

标签: awk merge grep

我有两个档案 f1.txt

From,Key,Count
abc.org,hello,5
abc.com,hello world,2
def.com,hi there,1
efg.com,hello world,1

f2.txt

h1,hello world
h2,hi there
h3,hello

我想要输出文件如下

From,Key,Count
abc.org,h3,5
abc.com,h1,2
def.com,h2,1
efg.com,h1,1

其中f1.txt的第二列与f2.txt的第二列匹配,并且该值被输出文件中的第二列f2.txt替换, (独特的部分)

我尝试使用如下的awk:

awk -F',' FNR==NR{a[$2]=$1;next} ($2 in a) {print $1,a[$1],$2}' f2 f1

但是它给出了错误而没有按预期工作

我应该在awk命令中修改什么?

更新: @Inian这个问题是基于一个公共字段合并这两个文件,我已经要求根据第二个文件的映射替换一个字段。

1 个答案:

答案 0 :(得分:1)

关注awk可能会有所帮助。

awk 'BEGIN{FS=OFS=","}FNR==NR{a[$NF]=$1;next} ($2 in a){$2=a[$2]} 1' f2.txt f1.txt

<强> 说明:

awk '
BEGIN{FS=OFS=","}  ##Starting BEGIN section here and setting field separator and output field separator as comma here.
FNR==NR{           ##Checking condition FNR==NR which will be TRUE when first Input_file named f2.txt is being read.
  a[$NF]=$1;       ##Creating an array named a whose index is $NF and value is $1.
  next}            ##Putting next keyword to skip all further statements as of now.
($2 in a){         ##Checking condition if $2 of Input_file2 named f1.txt is coming in aray a then do following.
  $2=a[$2]}        ##Setting current line $2 as value of array a whose index is $2.
1                  ##Printing current line by 1 here.
' f2.txt f1.txt    ##Mentioning Input_file(s) names here.

输出如下。

From,Key,Count
abc.org,h3,5
abc.com,h1,2
def.com,h2,1
efg.com,h1,1