Skip to content
19 October 2010 / avoulk

Bash floating arithmetics

These I was performing a series of simulations for my PhD and came across a problem i had not yet faced in my years of linux experience. You see, i had some .txt files ending with a phrase like

Total value increment is 10.71675%

and stuff like this. All i wanted is to get the increment and calculate the average value increment after the simulations had been performed. As the number of simulations needed is quite big ( >=500) this was not to be done by hand. So all I needed is a little foating point arithmetics for bash. That’s were the command bc comes. After a successful bc installation ( # pacman -Sy bc for Archlinux) i was able to create the following script:

#!/bin/bash

total=0;

counter=0;

cd sims/

for i in $(ls *.txt); do

counter=`echo $counter+1 | bc -l`

test=`tail -2 $i | head -1 | cut -d ' ' -f5 | cut -d '%' -f1`

total=`echo "$total+$test" | bc -l`

done

echo "$total/$counter" | bc -l

cd ..

That really did the trick, and I get an output stating the overall average value increment as calculated by the series of simulations I had performed.

=-=-=-=-=
Powered by Blogilo

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: