简体   繁体   中英

How to subtract two floating point numbers derived from a string

The floating point numbers come from an output string. Here is my sample code:

#!/bin/bash

    output="0.15 0.11"
    cputime=${output[0]}
    gputime=${output[1]}
    echo $cputime $gputime

    diff=`echo "$cputime - $gputime" | bc`
    echo $diff

Your code to separate the values can be better written with:

#!/bin/bash
output="0.15 0.11"
cputime=${output%% *}
gputime=${output##* }
diff=$(echo "$cputime - $gputime" | bc)
echo $diff

## and %% are, respectively, the removal-of-longest-prefix and removal-of-longest-suffix operators, deleting either everything from the first space onwards ( <space>* ) or everything up to the last space ( *<space> ).

The reason your current code doesn't work is because $output isn't an array for which the two values are in separate indexes, as it would be had you done something like:

output=("0.15" "0.11")

Alternatively, since you're already calling an external executable bc anyway, you could shorten the code with some added awk magic:

#!/bin/bash
output="0.15 0.11"
diff=$(awk '{print $1 - $2}' <<< "$output" | bc)
echo "$diff"

Assuming that the values are separated by a single space:

$ echo "$output"
0.15 0.11
$ tr ' ' - <<< "$output" | bc -l
.04

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM