awk multiply values contained in 2 different files

Hi Everyone !

I have two files with the same configuration
and I want to multiply corresponding values and write the result in a file.
Let say 2 header lines and then lines of values (with not constant number of columns):

more file1.txt --> 
BLABLABLA 
BLABLABLA 
1 2 3 4 
1 2 3 
1 2 
1 2 3
more file2.txt --> 
BLABLABLA 
BLABLABLA 
2 2 2 2
2 2 2 
1 1 
1 1 1

I want to have this result:

more file3.txt --> 
BLABLABLA 
BLABLABLA 
2 4 6 8 
2 4 6 
1 2 
1 2 3

Anyone has an idea ? Thanks in advance,
Y.

paste file1.txt file2.txt | awk '/^[0-9]/ {
                for(i=1;i<=NF/2;i++) {
                        s=s OFS $i*$(NF/2+1);
                }
                sub(/^ /,x,s);
                $0=s;
                s=""
} !/[0-9]/{
                $0=$1;
}1'

Note: Use nawk instead in Solaris or SunOS

Thanks a lot, I am very impress, really!
It works very well for my example but indeed I have forgot to say that
-each line start with 1 or more whitespace
-first value can be negative so first char can be "-"

The code gives you an idea on how to perform the arithmetic. Now why don't you modify the regexp as per you input file? Give it a try and let us know if you are stuck.

Of course, I am on it. Thanks again.

Hi bipinajith,
Nice code, (and it works for the given sample) but I think there is a typo. Did you intend to use:

                        s=s OFS $i*$(NF/2+i);

instead of

                        s=s OFS $i*$(NF/2+1);
1 Like

Yes Don, that was my bad. Thanks.

1 Like

Here is the code that I use now:

paste $filein1 $filein2 | nawk ' BEGIN {begdata=0}{
                if ((NR>2 && NF==12) || begdata==1) {
                  for(i=1;i<=NF/2;i++) {
                    printf(" %12.5E",$i*$(NF/2+i));
                  }
                  printf("\n");
                  begdata=1;
                 }
                else
                {
                  print substr($0,0,length($0)/2)
                }
              }' > $fileout

begdata is a boolean used to detect when my data begin (first time NF==12).

Thanks a lot bipinajith and also of course Don Cragun to detect the bug !!!

1 Like