Register
It is currently Wed Jul 23, 2014 7:56 pm

Bash script help subtracting numbers


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Sat Nov 07, 2009 9:41 am   

Joined: Sat Nov 07, 2009 9:39 am
Posts: 1
Hi i'm a newbie in scripting and i need help with developing a script that takes 2 lines of numbers from a file and subtracts them and echo's their result.

for instance i have a file test.txt with
Code:
200
50

now i have a script to ADD the two lines of number which is

Code:
value=0
while read var
do
value=$(($value + $var))
done < ~/test.txt
echo $value

but i can't figure out how too subract these two lines and echo the result


Top
 Profile  
 PostPosted: Mon Nov 09, 2009 2:22 am   

Joined: Mon Nov 17, 2008 7:25 am
Posts: 221
This is a job well done using "for-loops" :)

Code:
# cat test.txt
200
50
# cat test.sh
#!/bin/bash
value=0
for i in $(cat test.txt); do
   value=(($value + $i))
done


"For" makes an itteration for each "item" (seperated by a space character), meaning that if you have line like "200 40" then that will become 2 itterations.

Best regards
Fredrik Eriksson


Top
 Profile  
 PostPosted: Thu Nov 12, 2009 10:40 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 532
this can also be done basically like this:
Code:
$ while read line; do
> eval line$((++n))=$line
> test $n -eq 2 && { echo $((line1 + line2)); unset n; }
> done <test.txt
250


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 10 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP