Sample Header Ad - 728x90

Replacing math equations by result

2 votes
3 answers
167 views
What is the best way to replace, in a file, equations found using some predefined regex with the result. Let's say each equation formula is compatible with bc -l (basic calculator with float numbers handling). For example, saying equations are delimited by [[ and ]] (just as an example): Input would be: Results show that each unit should generate approx. [[7*9/2.0]]Wh per day. All the same ... Desired output: Results show that each unit should generate approx. 31.5Wh per day. All the same ... My best try: while read line; do if [[ $line =~ \[\[.*\]\] ]]; then equ=echo "$line" | sed "s|.*\[\[||" | sed "s|]].*||" res=echo "$equ" | bc -l | awk '{print $1+0}' new_line=echo $line | sed "s|\[\[.*]]|$res|" echo $new_line else echo $line fi done < $infile Output: Results show that each unit should generate approx. 31.5Wh per day. All the same ... But wonder if there would not be a simpler way (without the while loop). In addition, this will work if there is only one equation per line.
Asked by taalf (23 rep)
Jul 28, 2022, 07:14 AM
Last activity: Jul 29, 2022, 01:35 PM