Help needed with multiplying two values of two columns in a file

Hi, I am trying to multiply column#1 with column#2 using a shell script. How can I make a for-loop script using 1st column as "i" and the second column as "j" from the following file? Please feel free to share any alternative ways to multiplying column#1 with column#2.

.06     5.0000
.49     7.8750
.18     5.0000
.17     1.0000
.64     6.1250
.01     0.1250
.48     4.81250
.01     0.2500
.77     19.5000

Thanks in advance
:wall:

---------- Post updated at 08:20 PM ---------- Previous update was at 08:16 PM ----------

This is what I tried..... but did not work :frowning:

root@vna1(/)# for x in `awk '{print $1}' /tmp/temp6`
> do
> for j in `awk '{print $2}' /tmp/temp6`
> do
> echo "scale=3; $x * $y" | bc
> done
> done
syntax error on line 1 stdin
syntax error on line 1 stdin
syntax error on line 1 stdin
syntax error on line 1 stdin
syntax error on line 1 stdin
syntax error on line 1 stdin
syntax error on line 1 stdin

so, you already try in awk, why not write all by awk?

awk '{printf "%.3f\n", $1*$2}' infile
1 Like

Hi rdcwayx,

You rock, it works!! :slight_smile:

Thanks a bunch,
Momin

---------- Post updated at 02:28 PM ---------- Previous update was at 11:53 AM ----------

The output column in the solution above can have any number of values.... how can all those values be added when I we do not know the number of fields in the output?

added or multiplied? you mean you can have any number of columns rather than just two?

awk '{p=$1;for(i=2;i<=NF;i++)p*=$i;printf("%.3f\n",p)}'

example:

$ echo 3 .5 2 | awk '{p=$1;for(i=2;i<=NF;i++)p*=$i;printf("%.3f\n",p)}'
3.000
1 Like

Thanks neutronscott.

After adding up the two columns with rdcwayx's command, I had the output in form of one column. That column can have 15,16 or any number of values. My question was how to get the sum of all those values.

For example:

Output:
12
5
8
10

I want to get the sum of the values: 12+5+8+10=35. But I do not know how many values will be in the output, because output is different on each server.

assuming your input as

12
5
8
10

you can try this

awk '{while(i<NR){tot=tot+$1;i++}}END{print tot}' file

oh i see. i think chidori's sum would be for columns. you can sum it in same go as your multiplication. building on rdcwayx's code:

$ awk '{p=$1*$2;sum+=p;printf("%.3f\n", p)}END{printf("total: %.3f\n",sum)}' infile
0.300
3.859
0.900
0.170
3.920
0.001
2.310
0.003
15.015
total: 26.477