Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-file processing in awk

Tags:

sed

awk

I have file :

result.txt

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.

config.txt

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

like image 797
RATNESH TIWARI Avatar asked Mar 04 '23 11:03

RATNESH TIWARI


2 Answers

$ 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

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.

add a[$2] to the print if you want to print Max/Min/Median information.

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.

like image 162
karakfa Avatar answered Apr 06 '23 10:04

karakfa


You can try Perl as well

perl -lane ' BEGIN { @kv{qw(Min Median Max)}=(2,3,4);
            %kw=map{chomp;split} qx(cat ratnesh_config.txt) } 
            $p=$kv{$kw{$F[1]}}; print "$F[0] $F[1] $F[$p]" ' ratnesh_in.txt

with the given inputs:

$ cat ratnesh_config.txt
fruits Max
vehicle Median
study Min

$ cat ratnesh_in.txt
Apple fruits 10 20 30
Car  vehicle 40 50 60
Book study  70 80 90

$ perl -lane 'BEGIN { @kv{qw(Min Median Max)}=(2,3,4);%kw=map{chomp;split} qx(cat ratnesh_config.txt) } $p=$kv{$kw{$F[1]}}; print "$F[0] $F[1] $F[$p]" ' ratnesh_in.txt

Apple fruits 30
Car vehicle 50
Book study 70

$ perl -lane 'BEGIN { $kv{Min}=2;$kv{Median}=3;$kv{Max}=4;%kw=map{chomp;split} qx(cat ratnesh_config.txt) } $p=$kv{$kw{$F[1]}}; print "$F[0] $F[1] $F[$p]" ' ratnesh_in
.txt
Apple fruits 30
Car vehicle 50
Book study 70

$ perl -lane 'BEGIN { @kv{qw(Min Median Max)}=(2,3,4);%kw=map{chomp;split} qx(cat ratnesh_config.txt)} $p=$kv{$kw{$F[1]}}; print "@F[0,1,$p]" ' ratnesh_in.txt
Apple fruits 30
Car vehicle 50
Book study 70

$
like image 42
stack0114106 Avatar answered Apr 06 '23 10:04

stack0114106