2

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?

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

2 Answers 2

4

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.

2
  • 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!!
    – alloppp
    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};
    – malyy
    Jun 3, 2016 at 14:07
0
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
5

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.