I have file :


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

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.


fruits Max
vehicle Median
study Min

So I want to write a script which shows only that column number for the feature which is defined in config.txt file.

Expected output:

Apple fruits 30
Car vehicle 50
Book study 70

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

I can 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.


You need to map the feature names in the config.txt file to field indices in the result.txt file, e.g.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.