Arabisch
Arabisch

Reputation: 307

subtract one entry from another one in a column (in bash)

I have file1 that looks like:

50
120

I want to subtract these and store the result in a variable x. So the value of $x should be 70.

I am using bash. Thanks a lot.

Upvotes: 1

Views: 109

Answers (3)

John1024
John1024

Reputation: 113824

$ read -d '' a b <file1; echo $((b-a))
70

If you need floating point arithmetic:

$ read -d '' a b <file1; echo "$b - $a" | bc -l
70

Upvotes: 2

isosceleswheel
isosceleswheel

Reputation: 1546

For simple files with two values, use this awk command:

awk 'NR==1{a=$1}NR==2{b=$1}END{print b-a}' file1

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You can use awk like this:

x=$(awk 'NR>1{print $1-p} {p=$1}' file)
echo $x
70

Upvotes: 2

Related Questions