# How to multiply the array elements by itself

I have an array file and I need to do a math operation with the elements. The operation that I need to do is to multiply the element by itself, the to print it.

The input looks like this:

``````1: 6.1703
44 -0.27135
46 0.30270
44 0.52648

2: 6.1932
44 0.51448
46 0.14674
44 0.27957
46 -0.31834

3: 6.5664
45 -0.11892
45 0.66483
46 0.12505
``````

the first row of each array is the header. The math operation need to be done with the elements of the second column.

The output need to be:

``````1: 6.1703
44 0.07363
46 0.09162
44 0.27718

2: 6.1932
44 0.26468
46 0.02153
44 0.07815
46 0.10134

3: 6.5664
45 0.0141
45 0.44199
46 0.01563
``````

Any ideas or suggestion?

• can't get your math operation... Jun 3, 2016 at 13:02
• @malyy multiplying a number by itself is also called squaring :)
– mik
Jun 3, 2016 at 13:06

I would use `awk` to do this:

``````awk '\$1 ~ /^[0-9]+\$/ {\$2*=\$2}; 1'
``````

If first column is a number, multiply the second by itself. Then print entire line.

• Hi @milk, what modification I need to do if I want to multiply the squared number by a constant (for example times 2). Other question is what is the utility of ^[0-9] . If you can comment the lines will be greatful!! Jun 3, 2016 at 13:49
• ^[0-9] - it's regex expression in general read it like: if row in 1st column contains only number (where 1: doesn't suit) - then do math on the 2nd. similar espression - "\$1 !~ /:/ " means - if row doesn't contain symbol ":" - do the math. "multiply the squared number by a constant" - change to {\$2*=\$2*2}; Jun 3, 2016 at 14:07
``````while read line; do                                # for all lines in the file
i=0                                              # initialise loop counter
for param in \$line; do                           # for all words on the line
if [[ \$i -ne 0 ]]; then                        # if its not the first one
echo \$param | awk '{printf "%4.3f\n",\$1*\$1}' # print the result of squaring
fi                                             # (you could output to a file with >>)
((i++))                                        # increment loop counter
done
done < yourfilename                                # stream in your file
``````
• HI @Michael , something not work for your script. The output is only 4.3f Jun 3, 2016 at 13:44
• Jun 3, 2016 at 14:00
• @StéphaneChazelas Thanks. I'll have a read. Jun 3, 2016 at 14:32
• @alloppp that's because @Michael missed a `%` before `4.3f`
– mik
Jun 7, 2016 at 9:21
• I have added the missing `%` in `printf`.
– mik
Nov 16, 2016 at 18:57