awk 中的双文件处理

awk 中的双文件处理

我有文件:

结果.txt

Apple fruits 10 20 30
Car  vehicle 40 50 60
Book study  70 80 90

假设2nd column is a feature, 3rd column is Min, 4th column is Median, 5th column is Max我有另一个文件 config.txt,其中包含每个功能的属性,即

配置.txt

fruits Max
vehicle Median
study Min

所以我想编写一个脚本,仅显示config.txt文件中定义的特征的列号。

预期输出:

Apple fruits 30
Car vehicle 50
Book study 70

我正在关注此链接https://stackoverflow.com/a/40206489/10220825。以下是我尝试过的:

awk 'FNR==NR{arr[$2];next} $1 in arr {var =$2;print var}' result.txt config.txt

我可以将 result.txt 中定义的相应特征的属性(如最小值、最大值、中位数)保存在变量中,但无法显示该变量的列。请建议我如何打印相应列的列。

答案1

您需要将config.txt文件中的功能名称映射到文件中的字段索引result.txt,例如

awk '
  BEGIN {ind["Min"]=3; ind["Median"]=4; ind["Max"]=5} 
  NR==FNR {arr[$1] = ind[$2]; next} 
  $2 in arr {print $1,$2,$(arr[$2])}
' config.txt result.txt
Apple fruits 30
Car vehicle 50
Book study 70

相关内容