Desslock
Desslock

Reputation: 25

Awk multiply rows in file1 from single record in file2

I'm trying to multiply data from two files using awk. The particulars:

Given datafile (multiple records):

Col1 Col2 Col3 Col4 Col5 Col6a 100 200 300 400 500 600
Col1 Col2 Col3 Col4 Col5 Col6b 150 250 350 450 550 650
Col1 Col2 Col3 Col4 Col5 Col6c 20 30 40 50 60 70

Given lookupfile (1 record only):

Col1 Col2 Col3 Col4 Col5 Col6 2.2 4 3 5 4 6

Output:

Col1 Col2 Col3 Col4 Col5 Col6a 120 600 600 1600 1500 3000
Col1 Col2 Col3 Col4 Col5 Col6b 180 750 700 1800 1650 3250
Col1 Col2 Col3 Col4 Col5 Col6c 24 90 80 200 180 350

@JayPal provided a perfect solution to question above (with tab delimited formatting):

"BEGIN{FS=OFS=\"\t\"} NR==FNR{for(i=7;i<=NF;i++)fld[i]=$i;next}{for(i=7;i<=NF;i++)$i=($i*fld[i])-$i FS}1"

I've tried to glean from a couple of examples and see how to do matrix math with something like

FNR==NR{a[FNR]=$0}
{
    for(i=1;i<=NF;i++)
    {
        print($i*a[FNR])
    }
    printf(\"\n\")
}
lookup.txt data.txt >output.txt

Stuck on two things: limiting to field7+ and pulling only record1 from the lookup file.

Upvotes: 1

Views: 72

Answers (2)

glenn jackman
glenn jackman

Reputation: 247012

Noting that d * f - d = d * (f-1), we have

awk '
    NR==FNR {for (i=7; i<=NF; i++) f[i]=$i-1; next} 
    {for (i=7; i<=NF; i++) $i *= f[i]} 
    1
' lookupfile datafile

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77145

This should work:

awk 'NR==FNR{for(i=7;i<=NF;i++)fld[i]=$i;next}{for(i=7;i<=NF;i++)$i=($i*fld[i])-$i}1' lookupfile datafile

Output:

$ awk 'NR==FNR{for(i=7;i<=NF;i++)fld[i]=$i;next}{for(i=7;i<=NF;i++)$i=($i*fld[i])-$i}1' loo mul
Col1 Col2 Col3 Col4 Col5 Col6a 120 600 600 1600 1500 3000
Col1 Col2 Col3 Col4 Col5 Col6b 180 750 700 1800 1650 3250
Col1 Col2 Col3 Col4 Col5 Col6c 24 90 80 200 180 350

Upvotes: 1

Related Questions