Pramod Tiwari
Pramod Tiwari

Reputation: 169

How do we pass an array with list of data from one file while processing second file through AWK or any other method?

I have used the following file to reach the following result: enter image description here

The command that I have used to reach this result is as follows:

awk -F"\t" '(FNR>1)&&(NR==FNR){map[$1]=$4; next}($1 in map){$3=substr($3,2); for(i=4;i<7;i++){$i=($i*map[$1])}; print $0}' file2.txt file1.txt

This command works fine as long as the data in the column from Jan to Mar is same, but when the data is different, it creates problem because of map[$1]=$4. That is, I am only passing value of 4th column. I want to pass all the values from Jan to Mar and then multiply with corresponding value in another file.

I tried the following code:

awk -F"\t" '(FNR>1)&&(NR==FNR){{map[$1]=$0}; next}($1 in map){$3=substr($3,2); for(i=4;i<7;i++){split(map[$1],val);$i=($i*val[$i])}; print $0}' file2.txt file1.txt

Which sends the whole line and then splits it internally. I also tried passing the array directly to the map:

awk -F"\t" '(FNR>1)&&(NR==FNR){split($0,val); for(i=4;i<7;i++){map[$1][$i]=val[$i]}; print map[$1][$i]; next}($1 in map){$3=substr($3,2); for(i=4;i<7;i++){$i=($i*(map[$1][$i]))}; print $0}' file2.txt file1.txt

I don't mind using any other method for getting an answer to this question.I was thinking, do we have anyway of running an awk command inside another awk command? Final Edit:

awk -F"\t" '(FNR>1)&&(NR==FNR){map[$1]=$0; next}($1 in map){split(map[$1],temp);$3=substr($3,2); for(i=4;i<7;i++){$i=($i*temp[i])/12}; print $0}' file2.txt file1.txt

This is what worked in my case.

Upvotes: 2

Views: 94

Answers (1)

karakfa
karakfa

Reputation: 67507

your sample input/output has too much unrelated details. I have a simplified problem which you can utilize for your case.

$ head file{1,2}
==> file1 <==
1 10 20 30
2 11 21 31
3 12 22 32

==> file2 <==
1 6
2 7
3 8

$ awk 'NR==FNR{a[$1]=$0; next} 
       $1 in a{split(a[$1],v); print $1,$2,v[2]+v[3]+v[4]}' file1 file2

1 6 60
2 7 63
3 8 66

your missing ingredient is not using the whole record $0 and split function.

Upvotes: 2

Related Questions