Home > OS >  Extract numbers from a text file and do arithmetic operations
Extract numbers from a text file and do arithmetic operations

Time:09-26

After a program is finished, I obtain an output file(FILE) containing two consecutive lines including the word "number".

...some texts...
number1    3.145
number2    1.56
...some texts...

Only the two lines in FILE contain "number". The values vary depending on the input file for the calculation. Sometimes the program prints values in scientific notation like 6.145E-03.

What I would like to do is extract the two values from the two lines and do some arithmetic operations using bash commands. For example, say the two values are $num1 and $num2, 10*($num1 $num2)/($num1 - $num2). I think awk has an answer to this question.


p.s.

If not considering scientific notation leads a much simpler answer, I would try that solution. Scientific notation appears only some special cases which can be neglected.

CodePudding user response:

Assuming the sole purpose of this question is to use awk to parse a file and perform some math on the values extracted from the file ...

Same assumptions as from the previous question:

  • we want to match on lines that start with the string number
  • we will always find 2 matches for ^number from the input file
  • if there are more than 2 matches for ^number said matches will be ignored

One awk idea:

awk '
/^number/  { num[  i]=$2 }
END        { print (10 * (num[1]   num[2]) / (num[1] - num[2]) ) }
' file.dat

This generates:

-17.3874

For changing the output format we can use standard printf formats, eg:

awk '
/^number/  { num[  i]=$2 }
END        { printf "%.2f\n", (10 * (num[1]   num[2]) / (num[1] - num[2])) }
' file.dat

This generates:

-17.39

NOTE: - if there are any concerns about the reliability of the input data OP can add sanity checks (eg, on the matching lines is field #2 ($2) actually a number? what to do if num[1] - num[2] == 0 leads to a 'divide by 0' error?)

  • Related