1

I want your help in multiplying columns of one file by column of other another file where both files have the same number of columns and rows. I want the script to multiply the first column of the first file by the first column of the second file, the second column of the first file and the second column of the second file and so on.

Here is my sample data and the required output below

file1

2 3 4 4 . . . 
5 6 7 8 . . .
. . . . . . .

file2

3 4 8 10 . . . 
5 10 5 9 . . .
. . . . . . . 

Required output file will be

file1.file2

6 12 32 40 . . . 
25 60 35 72 . . . 
  • @Anthon, Thank you for editing my question!! – AiB Aug 28 '13 at 5:19
  • Abraham, I just refined what Drav had done. You can click the history (the link "edited XX mins ago" above the last editors' name), and see who changed what. Apart from the help on editing, that is often a good way to learn how to format things on Stack Exchange. – Anthon Aug 28 '13 at 5:36
  • Consider R for this kind of processing. It tends to be more capable and faster for numeric data than text-oriented tools such as awk. – Gilles Aug 28 '13 at 21:40
3

This should do it. Note it assumes the lines from both files have the same number of columns.

awk '
    {
            getline file2_line <"file2";
            split(file2_line, fields_from_file2);

            cur = 1;
            while ( cur <= NF )
            {
                    printf("%s ", $cur * fields_from_file2[cur]);
                    cur++;
            }

            printf("\n");
    }
    ' file1
  • perfect! It works great. Thank you very much!!! – AiB Aug 28 '13 at 5:17
3

Alternatively:

paste file1 file2 | awk '{h=NF/2;for (i=1;i<=h;i++) $i=$i*$(i+h);NF=h};1'

(assumes both files have the same number of columns and lines)

  • perfect!! your script also works for my big data – AiB Aug 28 '13 at 7:05

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.