在awk中处理两个文件 [英] Two-file processing in awk
问题描述
我有文件:
result.txt
result.txt
Apple fruits 10 20 30
Car vehicle 40 50 60
Book study 70 80 90
假设此处第二列是要素,第三列是Min,第四列是Median,第五列是Max.我还有另一个文件config.txt
,其中包含每个功能的属性,即
Assume here 2nd column is a feature, 3rd column is Min, 4th column is Median, 5th column is Max. I have another file config.txt
which contains a property for each feature i.e.
config.txt
config.txt
fruits Max
vehicle Median
study Min
所以我想编写一个脚本,只显示config.txt
文件中定义的功能的列号.
So I want to write a script which shows only that column number for the feature which is defined in config.txt
file.
预期输出:
Apple fruits 30
Car vehicle 50
Book study 70
我正在跟踪此链接 https://stackoverflow.com/a/40206489/10220825 .这是我尝试过的:
I am following this link https://stackoverflow.com/a/40206489/10220825. Here what I have tried:
awk 'FNR==NR{arr[$2];next} $1 in arr {var =$2;print var}' result.txt config.txt
我能够将属性(如Min,Max,Median)保留在result.txt
中定义的相应功能的变量中,但无法显示该变量的列.请为我建议一种有关如何为相应列打印列的方法.
I am able to hold the property (like Min, Max, Median) in a variable for the corresponding feature defined in result.txt
, but not able to display the column for that variable. Please suggest me an approach on how to print the column for the corresponding column.
推荐答案
$ awk 'BEGIN {m["Min"]=3; m["Median"]=4; m["Max"]=5}
NR==FNR {a[$1]=$2; next}
{print $1,$2,$m[a[$2]]}' config result
Apple fruits 30
Car vehicle 50
Book study 70
您需要保留min/median/max到对应列索引的映射,并在配置文件中查找需要打印的值.
you need to keep a map of min/median/max to the corresponding column index and lookup through the config file which value needs to be printed.
在打印件上添加a[$2]
.
NR==FNR {a[$1]=$2; next}
是awk
惯用法,用于将file1加载到以第一个字段和第二个字段为值索引的数组中,该数组本质上是字典或查找表.
NR==FNR {a[$1]=$2; next}
is the awk
idiom to load file1 into an array indexed with first field and field two as values, essentially a dictionary or a lookup table.
这篇关于在awk中处理两个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!