Guile
Guile

Reputation: 1494

Calculate difference between two number in a file

I want to know if it is possible to calculate the difference between two float number contained in a file in two distinct lines in one bash command line.

File content example :

Start at 123456.789
...
...
...
End at 123654.987

I would like to do an echo of 123654.987-123456.789

Is that possible? What is this magic command line ?

Thank you!

Upvotes: 0

Views: 3526

Answers (4)

Sergey Fedorov
Sergey Fedorov

Reputation: 2169

Bash doesn't support floating point operations. But you can split your numbers to parts and perform integer operations. Example:

#!/bin/bash
echo $(( ${2%.*} - ${1%.*} )).$(( ${2#*.} - ${1#*.} ))

Result:

./test.sh 123456.789 123654.987 
198.198

EDIT:

Correct solution would be using not command line hack, but tool designed or performing fp operations. For example, bc:

echo 123654.987-123456.789 | bc

output:

198.198

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246877

Here's a weird way:

printf -- "-%s+%s\n" $(grep -oP '(Start|End) at \K[\d.]+' file) | bc

Upvotes: 0

Andy1210
Andy1210

Reputation: 144

you can do this with this command:

start=`grep 'Start' FILENAME| cut -d ' ' -f 3`; end=`grep 'End' FILENAME | cut -d ' ' -f 3`; echo "$end-$start" | bc

You need the 'bc' program for this (for floating point math). You can install it with apt-get install bc, or yum, or rpm, zypper... OS specific :)

Upvotes: 2

Adam Liss
Adam Liss

Reputation: 48310

awk '
  /Start/ { start = $3 }      # 3rd field in line matching "Start"
  /End/ {
    end = $3;                 # 3rd field in line matching "End"
    print end - start         # Print the difference.
  }
' < file

If you really want to do this on one line:

awk '/Start/ { start = $3 } /End/ { end = $3; print end - start }' < file

Upvotes: 2

Related Questions