首页 > 解决方案 > awk 中的匹配

问题描述

请问这有什么问题?

awk 'NR == FNR { x[$1]=$1; next} { print x[$5], $0 }' A.dat B.txt > C.txt

我想:

如果文件 A.dat 的第一列等于文件 B.txt 的第一列,则打印文件 A.dat 的第五列和文件 B.txt 的其余部分

数据

50551.4765 7.8001 7.8001 1.0000 7
50458.7628 7.3914 7.3914 1.0000 7
50134.5127 4.4601 4.4601 1.0000 4
50476.5679 7.2830 7.2830 1.0000 7
50102.5924 4.5385 4.4912 1.0105 4

数据

50102.5924   72.220    
50103.5903   -3.800   
50107.5850  -23.670    
50108.5331   40.380    
50108.7620   -7.620    
50109.5345   75.810   
50109.7681   54.510   

期望的结果 C.txt

4   50102.5924   72.220 

标签: awk

解决方案


使用您显示的示例,请尝试以下代码。

awk 'FNR==NR{arr[$1]=$NF;next} ($1 in arr){print arr[$1],$0}' A.dat B.dat

解释:

awk '                ##Starting awk program from here.
FNR==NR{             ##Checking condition if FNR==NR which will be TRUE for A.dat
  arr[$1]=$NF        ##Creating arr with index of $1 and which has value of last field.
  next               ##next will skip all further statements from here.
}
($1 in arr){         ##Checking condition if 1st field is present in arr then do following.
  print arr[$1],$0   ##Printing arr with index of $1 and current line.
}
' A.dat B.dat        ##Mentioning Input_file names here.

推荐阅读