Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

bash - Extract numbers from a text file and do arithmetic operations

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", (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?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...